2009-11-15 52 views
1

我試圖從命令行得到一行作爲輸入。我的問題是我沒有得到整條線,但它被空間標記。C++ cout cin字符串操作

所以,如果我進了一些諸如「我喜歡數學了很多」,而不是讓

"you enterend: I like Math a lot" 

我得到follwoing:

EDITING MODE: Enter a command 
i like Math a lot 
you entered i 

EDITING MODE: Enter a command 
you entered like 

EDITING MODE: Enter a command 
you entered Math 

EDITING MODE: Enter a command 
you entered a 

EDITING MODE: Enter a command 
you entered lot 


void enterEditingMode(){ 
    editingMode = TRUE; 
    static string CMD = "\nEDITING MODE: Enter a command\n"; 
    string input; 
    while(editingMode == TRUE){ 
     cout << CMD; 
     cin >> input; 
     //we assume input is always correct 
     // here we need to parse the instruction 
     cout << "you entered " << input <<endl; 

回答

12

std::getline是讀取線的標準方式一次輸入。

您可以使用它像這樣:

std::getline(std::cin, string); 

它返回到它有一個隱式轉換到void*輸入流的引用,以便您可以檢查的成功很容易像這樣:

if (std::getline(std::cin, string)) 
{ 
    // successfully read a line... 
} 
+1

如果你想要一個c字符串,不要忘記cin.getline(char *,int)版本。 – 2009-11-15 00:24:29

+0

它沒有顯式轉換爲void *。它有一個顯式轉換爲一個在布爾上下文中可用的未指定類型。在你的實現中它可能碰巧是無效的,但這可能並不是全部。對初學者來說,它的結果可以更容易地解釋爲結果可以轉化爲布爾型的行爲。 – 2009-11-15 02:25:40

+0

其實,標準要求'operator void *'。它是'basic_ios'基類接口的一部分。 – 2009-11-15 09:26:44

1

cin.getline(input);

有關更多信息,請參閱http://www.cplusplus.com/reference/iostream/istream/getline/

+0

稱爲getline的'istream'成員函數全部採用'char'緩衝區和一個長度,而不是'字符串'。 – 2009-11-15 00:20:36

+0

我已經試過了,問題是由於代碼是在while循環中,所以首先它讀取新的行字符。所以當我甚至不輸入任何東西時,我總是會得到「你進入」。 – user69514 2009-11-15 00:29:49