コードを少し再設計することをお勧めします。たとえば、区切り文字が文字の場合、なぜ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