Announcement

Collapse
No announcement yet.

Lỗi khi viết code về chuỗi.(String)

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • [C++] Lỗi khi viết code về chuỗi.(String)

    Em đang viết bài tập sau: Nhập chuỗi st1, st2, vị trí 1 phần tử của chuỗi st1. Chèn chuỗi st2 vào chuỗi st1 từ vị trí được nhập. Em debug ko lỗi nhưng khi chạy lại báo lỗi. Mong mọi người giúp đỡ.
    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    #include <stdlib.h>
    void chenchuoi(char*st1,char*st2,int n)
    {
    	int m=strlen(st1),k=0;
    	char *t1,*t2;
    	t1=(char*)malloc(n+1);
    	t2=(char*)malloc(m-n+1);
    	strncpy(t1,st1,n);
    	t1[n]='\0';
    	for(int i=n;i<m;i++)
    	{
    		t2[k]=st1[i];
    		++k;
    	}
    	t2[m-n]='\0';
    	strcat(t1,st2);
    	strcat(t1,t2);
    	puts(t1);
    }
    void main()
    {
    	int n;
    	char *st1,*st2;
    	st1=(char*)malloc(sizeof(st1));
    	st2=(char*)malloc(sizeof(st2));
    	printf("Nhap chuoi st1: ");
    	gets(st1);
    	printf("Nhap vi tri can chen: ");
    	scanf("%d",&n);
    	printf("Nhap chuoi can chen: ");
    	gets(st2);
    	chenchuoi(st1,st2,n);
    	getch();
    }

  • #2
    của em đây
    PHP Code:
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    #include <stdlib.h>
    void chenchuoi(char*st1,char*st2,int n)
    {
        
    int m=strlen(st1),k=0;
        
    char *t1,*t2;
        
    t1=(char*)malloc(n+1);
        
    t2=(char*)malloc(m-n+1);
        
    strncpy(t1,st1,n);
        
    t1[n]='\0';
        for(
    int i=n;i<m;i++)
        {
            
    t2[k]=st1[i];
            ++
    k;
        }
        
    t2[m-n]='\0';
        
    strcat(t1,st2);
        
    strcat(t1,t2);
        
    puts(t1);
    }
    void main()
    {
        
    int n;
        
    char *st1,*st2;
        
    st1=(char*)malloc(sizeof(st1));
        
    st2=(char*)malloc(sizeof(st2));
        
    printf("Nhap chuoi st1: ");
        
    fflush(stdin);
        
    gets(st1);
        
    printf("Nhap vi tri can chen: ");
        
    scanf("%d",&n);
        
    printf("Nhap chuoi can chen: ");
        
    fflush(stdin);
        
    gets(st2);
        
    chenchuoi(st1,st2,n);
        
    getch();

    không chạy vì lý do em chua xóa dữa liệu(theo anh như thế);
    hình anh chạyhelp.png

    Comment


    • #3
      Em cám ơn anh. Anh cho em hỏi luôn là lệnh fflush(stdin) có chức năng gì anh?

      Comment


      • #4
        Originally posted by 12520332 View Post
        Em cám ơn anh. Anh cho em hỏi luôn là lệnh fflush(stdin) có chức năng gì anh?
        dùng để xóa ký tự "rác" nha, anh chỉ khuyên em nên dùng fflush(stdin) trước gets(), hai đứa này luôn đi chung, cho dể nhớ

        Comment

        LHQC

        Collapse
        Working...
        X