2015-07-10 28 views
0

我正在嘗試編寫一個C程序,它將n作爲整數輸入,然後輸入n字符串。當我運行程序時,需要一個輸入小於n的問題。如果我輸入1作爲第一個輸入,程序就會終止。這裏是代碼:C中輸入字符串時的問題

int n; 
scanf("%d", &n); 
char str[101]; 

while (n--) { 
    fgets(str, 101, stdin); 
    // other stuff... 
} 

我在做什麼錯在這裏?

回答

1

請記住,按Enter鍵也會向流發送字符。你的程序無法解釋這一點。使用格式scanf(%d%*c)放棄第二個字符。如果你使用scanf()人數爲字符串輸入

int main(void) { 

    int n; 

    scanf("%d%*c", &n); 

    char str[101]; 

    while (n--) 
    { 
     fgets(str, 101, stdin); 

     // other stuff..... 
    } 

} 
3

你的程序工作。

#include <stdio.h> 

int main() 
{ 
    int n; 
    char str[101]; 
    scanf("%d", &n); 
    while (n--) 
    { 
     scanf("%s", str); 
    } 
    return 0; 
} 

但它無疑更好地使用fgets()所有的輸入。

#include <stdio.h> 

int main() 
{ 
    int n; 
    char str[101]; 
    fgets(str, 100, stdin); 
    sscanf(str, "%d", &n); 
    while (n--) 
    { 
     fgets(str, 100, stdin); 
    } 
    return 0; 
} 

我幾乎要提醒你,因爲你首先使用fgets(),你會知道,它保留了newline輸入字符串的結尾。

+2

注:最好使用'與fgets(STR,STR的sizeof,標準輸入);'1)是應該是101不是100和2)避免幻數。 +1「,以便更好地爲所有輸入使用fgets()。」 – chux

1
int n; 
scanf("%d", &n); 
char str[101]; 

while (n--) 
{ 
fgets(str, 101, stdin); 
// other stuff... 
} 

在此,當你進入n和鍵盤'\nENTER存儲在stdin因此爲fgets遭遇newline character如果回報。

因此使用此之後scanf -

char c ; 
while((c=getchar())!=NULL && c!='\n');