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