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]);

我应该能够在字符串“test”中输入一个字符串,直到我输入结束字符,但是如果我输入一个双新行,它就无法识别结束字符,也不会结束输入。

这是输出:

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

}
do it}
damn}
4

2 回答 2

1

You may want to redesign your code a little bit, e.g. if the delimiter is a character, then why reading a string (and using a kind of obscure syntax like "c.c_str()[0]" - at least just use c[0] to extract the first character from the string)? Just read the single delimiter character.

Moreover, I see no unexpected results from getline().

If you try this code:

#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;
}

the output is as expected, e.g. the input string "hello!world" is truncated at the delimiter "!" and the result is just "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
于 2013-03-03T11:47:14.067 回答
0

将代码更改为

获取线(cin,str,c[0]);

于 2013-03-03T10:54:57.573 回答