2011-04-22 54 views
6

我必須從控制檯讀取整行,並將其存儲到std::stringchar陣列中,例如 。如何從控制檯讀取行並將其存儲到C++中的字符串?

"Hi this is balaji" 

現在我必須閱讀上面的字符串並將其存儲到string。我嘗試使用getline()函數。

+1

什麼問題? getline()沒有工作嗎? – 2011-04-22 20:52:33

+0

我推薦一本好書,[任何這些](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)都可以。 – Xeo 2011-04-22 20:58:57

回答

17

嘗試:

#include <string> 
#include <iostream> 

int main() 
{ 
    std::string line; 

    std::getline(std::cin, line); // read a line from std::cin into line 

    std::cout << "Your Line Was (" << line << ")\n"; 

    std::getline(std::cin, line); // Waits for the user to hit enter before closing the program 
} 
+0

我試過了,但控制並沒有停下來,我的代碼如下: – balaji 2011-04-22 21:05:22

+2

@balaji:不要。 – 2011-04-22 23:35:21

0

也許有什麼問題,你如何使用cin.getline()?

cin.getline (name,256); 

C++ refence for getline()

+2

請勿使用該版本的getline。如果該行大於256個字符,甚至更糟的是緩衝區小於256個字符會發生什麼情況。 – 2011-04-22 21:00:51

0

也許

string a; 
cin >> a; 

cout << a << endl; 

或類似的東西?

+0

讀取空格分隔的單詞。 – 2011-04-22 21:01:10

+0

呃...不! :)它確實讀取用戶輸入。 – nagymafla 2011-04-22 21:04:29

+2

它從用戶那裏讀取一些輸入,但是OP特別要求閱讀「整條線」的幫助,而這不是。 – 2011-04-22 21:05:53

相關問題