2017-01-02 37 views
0

我想要做的是創建一個收集字符串(在這種情況下名稱)的循環,然後通過字符的請求詢問用戶是否他想繼續插入更多。無法做出正確的採集循環 - C

#include <stdio.h> 
#include <string.h> 
void main(){ 
    char c, str[5][20]; 
    int i=0; 
    do { 
     printf("What's your name?\n"); 
     gets(str[i]); 
     i++; 
     printf("Do you want to insert more?\n"); 
     scanf("%c\n",&c); 
    } while (c=='y'); 
} 

,我讀他們lenght是任意的字符串的數量不是我在使用,如果有使用這種收購的「正確的方式」,只是想知道,或者我應該麻煩放棄它。

+0

請描述你的程序的當前行爲,包括有什麼樣的錯誤/缺失行爲。但是,是的,這絕對有可能做到你想要的。一般的方法是爲每個字符串選擇一個MAX_LENGTH,併爲每個名稱使用動態內存分配。 – kaylum

+1

請不要使用'gets'。它很容易出現許多問題,包括安全性。嘗試使用'fgets'代替。 – MateoConLechuga

+0

你的問題到底是什麼? – melpomene

回答

-3

這變得更容易,扭轉它的時候: ,而不是要求更多,等待空的輸入

#include <stdio.h> 
#include <string.h> 
void main(){ 
     char c, str[5][20]; 
     int i=0; 
     do { 
      printf("What's your name? - (end list with empty string)\n"); 
      gets(str[i]); 
      i++; 
     } while (len(str[i-1] > 0) && (i < 5)); 
    } 
+1

呃。'' gets'可以溢出,'len'是什麼? – DevNull

-3

你可以這樣來做。

#include <stdio.h> 
#include <string.h> 

int main() { 
    char c[3], str[5][20]; 
    int i = 0; 
    do { 
     printf("What's your name?\n"); 
     if (fgets(str[i], sizeof str[i], stdin)) { 
      // input has worked, do something with data 
      i++; 
     } 
     printf("Do you want to insert more?\n"); 
     if (fgets(c, 3, stdin)) { 
      // input has worked, do something with data 
     } 
    } while (c[0] == 'y'); 
} 

測試

What's your name? 
Mallory 
Do you want to insert more? 
y 
What's your name? 
Carol 
Do you want to insert more? 
no 

Process finished with exit code 0 
+0

和'sizeof&c'給出的指針大小不是'char'的大小,也可能導致緩衝區溢出 – kaylum

+0

試圖使用一個整數作爲緩衝區的地址。 – melpomene