2014-04-01 40 views
0

我想做一個程序,用戶輸入一個字符串,然後如果他們想輸入他們想要替換的字母和什麼。我想用malloc來設置數組,但我怎麼用scanf來做到這一點?malloc與用戶輸入

請有人幫忙。

謝謝!

這是什麼程序,纔去更換方法如下:

char *s,x,y; 

printf("Please enter String \n"); 
scanf("%s ", malloc(s)); 

printf("Please enter the character you want to replace\n"); 
scanf("%c ", &x); 

printf("Please enter replacment \n"); 
scanf("%c ", &y); 

prinf("%s",s); 
+1

我想你想要POSIX ['getline()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html)(不是C99標準的一部分)。 – pmg

+0

您對malloc的使用是非常錯誤的:Malloc獲取字節數並返回一個指針。你傳給它一個指針。 –

回答

0
scanf("%s ", malloc(s)); 

這是什麼意思?未初始化的是指針,它可以具有任何值,例如0x54654,它是未定義的行爲。

你的代碼應該是,

int size_of_intput = 100; //decide size of string 
s = malloc(size_of_intput); 
scanf("%s ", s); 
+2

您應該__always__確保不會造成緩衝區溢出。 A> = 100個字符的用戶輸入可能會導致堆棧損壞!通過'scanf(「%99s」,s)',並檢查scanf的返回值。 –

+0

@mic_e偉大的建議。不知道'%99s'可能。 –

0

你無法知道用戶輸入的大小提前,所以你需要在用戶輸入尚未結束動態地分配更多的內存。

一個例子是:

//don't forget to free() the result when done! 
char *read_with_alloc(FILE *f) { 
    size_t bufsize = 8; 
    char *buf = (char *) malloc(bufsize); 
    size_t pos = 0; 

    while (1) { 
     int c = fgetc(f); 

     //read until EOF, 0 or newline is read 
     if (c < 0 or c == '\0' or c == '\n') { 
      buf[pos] = '\0'; 
      return buf; 
     } 

     buf[pos++] = (char) c; 

     //enlarge buf to hold whole string 
     if (pos == bufsize) { 
      bufsize *= 2; 
      buf = (char *) realloc((void *) buf, bufsize); 
     } 
    } 
} 

務實替代解決方案將是限制的BUF大小(例如,256個字符),並且,以確保僅字節的該編號被讀出:

char buf[256]; //alternative: char *buf = malloc(256), make sure you understand the precise difference between these two! 
if (scanf("%255s", buf) != 1) { 
    //something went wrong! your error handling here. 
}