2

特定の操作を実行するための入力として空行をチェックしたい。cin.peek() を使用して '\n' と等しいかどうかを確認しようとしましたが、意味がありません。

a

b

c

空行 (ここで、アクションを実行したい)

a

私はこのコードを試しました:

char a,b,c;
cin>>a;
cin>>b;
cin>>c;
if(cin.peek()=='\n') {
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
4

1 に答える 1

6

を使用getlineしてから、文字列を処理します。ユーザーが空の行を入力した場合、文字列は空になります。そうでない場合は、文字列に対してさらに処理を行うことができます。に入れ、istringstreamから来ているかのように扱うこともできcinます。

次に例を示します。

std::queue<char> data_q;
while (true)
{
    std::string line;
    std::getline(std::cin, line);

    if (line.empty())    // line is empty, empty the queue to the console
    {
        while (!data_q.empty())
        {
            std::cout << data_q.front() << std::endl;
            data_q.pop();
        }
    }

    // push the characters into the queue
    std::istringstream iss(line);
    char ch;
    while (iss >> ch)
        data_q.push(ch);
}
于 2013-04-14T00:48:07.523 に答える