Reputation: 927
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]);
I should be able to put into the string "test" a string until I digit the ending char but if I enter a double new line it doesn't recognize the ending char and it doesn't end the input.
This is the output:
Insert the character that ends the input:
}
Insert the string:
asdf
}
do it}
damn}
Upvotes: 1
Views: 2431
Reputation: 43044
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
Upvotes: 1