使用cin检查空行

Sam*_*awy 1 c++

我想检查空行作为执行特定操作的输入.我试图使用cin.peek()并检查它是否等于'\n',但它没有意义.

一个

b

C

空行(这里,我想执行我的动作)

一个

我试过这段代码:

char a,b,c;
cin>>a;
cin>>b;
cin>>c;
if(cin.peek()=='\n') {
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 5

使用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);
}
Run Code Online (Sandbox Code Playgroud)