2014-04-05 15 views
1

我在C++如下因素的代碼:使用歸檔輸入的C++中該程序有什麼問題?

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

using namespace std; 

int main(int argc, char **argv) 
{ 
    int N; 
    string s; 
    char str[100]; 
    scanf("%d",&N); 

    for(int i=0; i<N; i++) 
    { 
     fflush(stdin); 
     fgets(str,100,stdin); 
     s = str; 
     cout << s << endl; 
    } 

    return 0; 
} 

的代碼保存在檔案TEST.CPP。

使用在Linux Ubuntu的所述終端針對編譯:

g++ -c hello.cpp 
g++ -o hello hello.o 

我有一個歸檔test.in在將成爲輸入:

5 
God of War 
Grand Theft Auto 
The Smurfs 
Final Fantasy 
Call of Duty 

在終端乳寧命令:

./test < test.in 

輸出將是:

[email protected]:~/Documentos$ ./teste < teste.in 


God of War 

Grand Theft Auto 

The Smurfs 

Final Fantasy 

[email protected]:~/Documentos$ 

因爲「使命召喚」這一行被跳過了嗎?

+0

編譯'G ++ -Wall -g -o HELLO.CPP和hello'學習如何使用'gdb'調試器(例如開始與'GDB hello') –

+0

'test.cpp'那麼爲什麼'hello.cpp'被編譯? – P0W

+2

不使用'fflush(stdin);' – BLUEPIXY

回答

3

scanf("%d",&N); 

不會跳過超出線的端部,因此,第一fgets(str,100,stdin);剛剛讀取其中5給出線的其餘部分。請注意輸出中額外的空白行,因爲您已發佈它?