2013-03-03 137 views
1
string str, temp; 

string c; 

cout << "Insert the character that ends the input:" << endl; 

getline(cin, c); 

cout << "Insert the string:" << endl; 

getline(cin, str, c.c_str()[0]); 

我應該能夠投入到字符串「測試」的字符串,直到我的數字結束字符,但如果我進入一個新的雙行不認識的結局字符,它不會結束輸入。C++函數getline()並沒有結束輸入

這是輸出:

Insert the character that ends the input: 
} 
Insert the string: 
asdf 

} 
do it} 
damn} 
+0

你的代碼和示例輸出是不同的。你能發佈正確的一個嗎 – Pradheep 2013-03-03 10:58:03

+0

你的代碼適合我。但是我會用'char'來代替'c'。 – cnicutar 2013-03-03 10:58:17

+0

'c [0]'而不是'c.c_str()[0]'也可以工作,但我無法重現這種行爲(g ++ -4.7,Ubuntu 12.10)。 – Cubic 2013-03-03 10:59:01

回答

1

您可能需要重新設計您的代碼,例如,如果分隔符是一個字符,那麼爲什麼要閱讀一個string(並使用一種模糊的語法,如「c.c_str()[0]」 - 至少只是使用c[0]從字符串中提取第一個字符)?只需閱讀單個分隔符。

此外,我看到從getline()沒有意外的結果。

如果你試試這個代碼:

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    cout << "Insert the character that ends the input: " << endl; 
    char delim; 
    cin >> delim; 

    string str; 
    cout << "Insert the string: " << endl; 
    getline(cin, str, delim); 

    cout << "String: " << str << endl; 
} 

如預期的輸出,例如輸入字符串「hello!world」的分隔符「!」被截斷,其結果就是「hello」:

C:\TEMP\CppTests>cl /EHsc /W4 /nologo /MTd test.cpp 
test.cpp 

C:\TEMP\CppTests>test.exe 
Insert the character that ends the input: 
! 
Insert the string: 
hello!world 
String: 
hello 
+0

謝謝大家,我發現這個錯誤出現在這個輸入的算法中。 – fpiro07 2013-03-03 12:13:06

0

更改代碼以

函數getline(CIN,STR,C [0]);

+0

@Predheep - c是一個字符,它不允許爲一個純字符類型下標。 – suspectus 2013-03-03 10:59:27

+0

@suspectus c是一個字符串。 – Cubic 2013-03-03 10:59:47

+0

@Cubic - 對不起,我現在看到它。帖子已被編輯。 – suspectus 2013-03-03 11:00:54

0

結果是OK。 它不應該結束立即輸入。它讀取直到'\ n',然後它存儲您的輸入,直到讀取分隔符。

定界符getline

分隔字符。當讀取此字符時,停止提取連續的 字符的操作。該參數爲 可選,如果未指定,則函數將'\ n'(換行符 字符)作爲分隔符。

例如,如果你的分隔符是#,你輸入abcd#hello,其結果將是abcd

+0

在這種情況下,分隔符是'}'。除非他的終端有一個奇怪的一天,這應該工作。 – Cubic 2013-03-03 11:00:45

+0

但是,它不能識別delim char並且不會繼續執行程序的其餘部分 – fpiro07 2013-03-03 11:02:19

+0

但是,如果我編寫'abcd \ n \ n#'程序不會停止輸入 – fpiro07 2013-03-03 11:10:47