2012-05-05 154 views
28

我試圖使用C++標準輸入讀取,使用此代碼從標準輸入讀取C++

#include <iostream> 
using namespace std; 

int main() { 
    while(cin) { 
     getline(cin, input_line); 
     cout << input_line << endl; 
    }; 
    return 0; 
} 

當我編譯,我得到這個錯誤..

[[email protected] krisdigitx]# g++ -o capture -O3 capture.cpp 
capture.cpp: In function âint main()â: 
capture.cpp:6: error: âinput_lineâ was not declared in this scope 

任何想法什麼缺失?

回答

53

您尚未定義變量input_line

補充一點:

string input_line; 

並添加此包括。

#include <string> 

這裏是完整的例子。我也在while循環後刪除了分號,並且您應該在的範圍內正確檢測流的結束。

#include <iostream> 
#include <string> 

int main() { 
    for (std::string line; std::getline(std::cin, line);) { 
     std::cout << line << std::endl; 
    } 
    return 0; 
} 
+0

由於現在loganfsmyth..works .. – krisdigitx

+4

而不泄漏串入環境範圍:'用於(字符串s;函數getline(CIN,S);){COUT <<小號<< ENDL; }'。此外,暗示'返回0',不需要拼出來。 –

+1

@krisdigitx如果解決了您的問題,請接受答案。 – loganfsmyth