17

次のコードを使用しています。

#include <iostream>
using namespace std;

int main(int argc, char **argv) {
    string lineInput = " ";
    while(lineInput.length()>0) {
        cin >> lineInput;
        cout << lineInput;
    }
    return 0;
}

次のコマンドを使用します。 echo "Hello" | test.exe

この結果は、「Hello」を出力する無限ループです。単一の「Hello」を読み取って印刷するにはどうすればよいですか?

4

2 に答える 2

28
string lineInput;
while (cin >> lineInput) {
  cout << lineInput;
}

完全な行が本当に必要な場合は、次を使用します。

string lineInput;
while (getline(cin,lineInput)) {
  cout << lineInput;
}
于 2011-03-26T23:39:27.840 に答える
12

抽出にcin失敗した場合、ターゲット変数は変更されません。したがって、プログラムが最後に正常に読み取った文字列はlineInput.

確認する必要がありcin.fail()Erik はそれを行うための好ましい方法を示しました

于 2011-03-26T23:44:11.827 に答える