简体   繁体   English

使用getline忽略用户输入中的选项卡和换行符

[英]Ignore tabs and line breaks in user input using getline

I'm writing a program that takes user input using getline (I must use getline ) and spits it back out to the screen. 我正在编写一个程序,该程序使用getline获取用户输入(我必须使用getline ),然后将其吐回到屏幕上。 It is also supposed to ask again if the input was blank. 还应该再次询问输入是否为空白。 I'm having trouble with handling input that has multiple line breaks and tabs. 我在处理具有多个换行符和制表符的输入时遇到麻烦。

I've gotten it to almost work but it's looping through a few times and I can't figure out how to fix it/do it better. 我已经知道它几乎可以正常工作了,但是它已经循环了几次,我不知道该如何解决/做得更好。 Here's the code: 这是代码:

string name;

while(true) 
{
    cout << "What is your name?" << endl;

    getline(cin, name, '\n');
    if (!name.empty()) 
    {
        break;
    }
}
cout << "Hello " << name << "!" << endl;

return 0; 

Here's the input: 这是输入:

\n
\n
John\n
Doe\n

The output I want is supposed to look like this: 我想要的输出应该看起来像这样:

What is your name?
Hello John Doe!

My output looks like this: 我的输出如下所示:

What is your name?
What is your name?
What is your name?
Hello John!

It's possible I don't understand your requirements, but if all you want to do is to collect a first and last name from the user on separate lines (while ignoring any tabs), you can do it like this. 我可能不理解您的要求,但是如果您要做的只是在分开的行中收集用户的姓氏和名字(而忽略任何选项卡),则可以这样做。

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string first;
    std::string last;
    std::cout << "What is your name?\n";
    while (first.empty())
    {
        std::getline(std::cin, first);
        // remove all tabs from input
        first.erase(std::remove(first.begin(), first.end(), '\t'), first.end());
    }
    while (last.empty())
    {
        std::getline(std::cin, last);
        // remove all tabs from input
        last.erase(std::remove(last.begin(), last.end(), '\t'), last.end());
    }
    std::string name = first + " " + last;
    std::cout << "Hello, " << name << "!\n";
    return 0;
}

Your user will be allowed to hit return/enter and tab until they are delirious. 您的用户将被允许点击返回/输入和制表符,直到他们发狂为止。 Until std::getline() gets some non-tabbed input it doesn't matter how many newlines or tabs happen. 直到std::getline()得到一些非制表符的输入,才有多少换行符或制表符发生。 From your question this seems like what you want. 从您的问题来看,这似乎是您想要的。 You can find more information on the STL algorithm that I used to remove tabs with std::remove here . 您可以找到有关STL算法的更多信息,该算法用于通过std::remove 在此处删除选项卡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM