简体   繁体   中英

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. 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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