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

終了文字を数字で表すまで文字列を「テスト」できるはずですが、改行を2行入力すると、終了文字が認識されず、入力が終了しません。

これは出力です:

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

}
do it}
damn}
4

2 に答える 2

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
于 2013-03-03T11:47:14.067 に答える
0

コードをに変更します

getline(cin、str、c [0]);

于 2013-03-03T10:54:57.573 に答える