2014-04-17 109 views
0
#include <stdio.h> 
#include<stdlib.h> 
#include <string.h> 
int main(void) { 
    char a[1001]; 
    int t,i; 
    scanf("%d",&t); 

    while(t--) 
    { 
     fflush(stdin); 
     gets(a); 
     printf("%d\t",t); 
     puts(a); 

    } 
    return 0; 
} 

輸入:如何輸入兩個字符串?

2 
die another day. 
i'm batman. 

輸出繼電器:

1 
0 die another day. 

預期輸出:

1 die another day. 
0 i'm batman. 

請人幫忙如何接受沒有任何錯誤不止一個字符串。 進入2後,我能夠看到我的get獲取換行符作爲第一個字符串,然後第二個字符串正確。 在此先感謝

+2

技術上'fflush(stdin)'是未定義的行爲。它在所有系統和平臺上都不受支持。 –

+0

任何想法都可以使程序在幾乎編譯器上正常工作?包括在線編譯器。 –

回答

2

停止使用scanf()stdin來讀取輸入。千萬不要致電fflush(stdin);,但如果您停止使用scanf(),您將不再需要。

使用fgets()將整行讀入適當大小的字符串緩衝區,然後解析所得結果。解析字符串的一個很好的功能是sscanf(),它就像scanf(),只不過它從字符串中讀取。

這會容易得多,不那麼煩人,而且通常更好。哦,當然從來沒有使用gets()

像這樣(未經):

#include <stdio.h> 
#include <stdlib.h> 

int main(void) 
{ 
    char line[256]; 

    if(fgets(line, sizeof line, stdin)) 
    { 
    int count; 
    if(sscanf(line, "%d", &count) == 1) 
    { 
     while(count > 0) 
     { 
     if(fgets(line, sizeof line, stdin)) 
     { 
      printf("%s", line); 
      --count; 
     } 
     else 
      break; 
     } 
    } 
    } 
    return EXIT_SUCCESS; 
} 
+0

我可以請你給一個例子如何使用fgets() –

+0

你可以解釋流程我不能獲得方法提到的功能 –

+0

@tech_boy我做了'fgets()'和'sscanf()'到鏈接中,所以你可以閱讀文檔來弄清楚這些功能究竟是如何工作的。 – unwind

0

不使用fflush(標準輸入)。使用getchar()清除scanf()作爲後留下的[進入]人物,

#include <stdio.h> 
#include<stdlib.h> 
#include <string.h> 
int main(void) { 
    char a[1001]; 
    int t,i; 
    scanf("%d",&t); 
    getchar(); 
    while(t--) 
    { 

     gets(a); 
     printf("%d\t",t); 
     puts(a); 

    } 
    return 0; 
} 

它的工作原理。