使用cin检查空行 [英] Check for empty line using cin

查看:750
本文介绍了使用cin检查空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to check for an empty line as an input to perform a specific operation. I tried to use cin.peek() and check if it is equal to '\n', but it does not make sense.


a

a

b

c

空行(此处,我要执行我的操作)

empty line (here, I want to perform my action)


a

a

我试过这个代码:

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


推荐答案

使用 getline ,然后处理字符串。如果用户输入空行,则字符串将为空。如果他们没有,你可以做进一步处理的字符串。您甚至可以将它放在 istringstream 中,并将其视为来自 cin

Use getline, then process the string. If the user entered an empty line, the string will be empty. If they didn't, you can do further processing on the string. You can even put it in an istringstream and treat it as if it's coming from 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);
}

这篇关于使用cin检查空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆