在 C++ 中使用 getline 忽略空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4876959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:49:47  来源:igfitidea点击:

Ignore Spaces Using getline in C++

c++stringignorespacegetline

提问by Cistoran

Hey, I'm trying to write a program that will accept new tasks from people, add it to a stack, be able to display the task, be able to save that stack to a text file, and then read the text file. The issue comes when I am trying to accept input from the user, whenever you enter a string with a space in it, the menu to choose what to do just loops. I need a way to fix this. Any help would be greatly appreciated.

嘿,我正在尝试编写一个程序,该程序将接受人们的新任务,将其添加到堆栈中,能够显示任务,能够将该堆栈保存到文本文件中,然后读取文本文件。当我试图接受用户的输入时,问题就出现了,每当你输入一个带有空格的字符串时,选择做什么的菜单就会循环。我需要一种方法来解决这个问题。任何帮助将不胜感激。

// basic file io operations
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;

int main () {
    //Declare the stack
    stack<string> list;

    //Begin the loop for the menu
    string inputLine;
    cout << "Welcome to the to-do list!" << endl;

    //Trying to read the file
    ifstream myfile ("to-do.txt");
    if(myfile.is_open()){

        //read every line of the to-do list and add it to the stack
        while(myfile.good()){
            getline(myfile,inputLine);
            list.push(inputLine);
        }
        myfile.close();
        cout << "File read successfully!" << endl;
    } else {
        cout << "There was no file to load... creating a blank stack." << endl;
    }

    int option;

    //while we dont want to quit
    while(true){
        //display the options for the program
        cout << endl << "What would you like to do?" << endl;
        cout << "1. View the current tasks on the stack." << endl;
        cout << "2. Remove the top task in the stack." << endl;
        cout << "3. Add a new task to the stack." << endl;
        cout << "4. Save the current task to a file." << endl;
        cout << "5. Exit." << endl << endl;

        //get the input from the user
        cin >> option;

        //use the option to do the necessary task
        if(option < 6 && option > 0){
            if(option == 1){
                //create a buffer list to display all
                stack<string> buff = list;
                cout << endl;
                //print out the stack
                while(!buff.empty()){
                    cout << buff.top() << endl;
                    buff.pop();
                }
            }else if (option == 2){
                list.pop();
            }else if (option == 3){
                //make a string to hold the input
                string task;
                cout << endl << "Enter the task that you would like to add:" << endl;
                getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
                cin.ignore();

                //add the string
                list.push(task);
                cout << endl;
            }else if (option == 4){
                //write the stack to the file
                stack<string> buff = list;
                ofstream myfile ("to-do.txt");
                if (myfile.is_open()){
                    while(!buff.empty()){
                        myfile << buff.top();
                        buff.pop();
                        if(!buff.empty()){
                            myfile << endl;
                        }
                    }
                }
                myfile.close();
            }else{
                cout << "Thank you! And Goodbye!" << endl;
                break;
            }
        } else {
            cout << "Enter a proper number!" << endl;
        }
    }
}

回答by Vladimir

You have to add cin.ignore()right after options is chosen:

您必须cin.ignore()在选择选项后立即添加:

//get the input from the user
cin >> option;
cin.ignore();

And cin.ignore()is not necessary after your getline:

cin.ignore()你后是没有必要的getline

    getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
        //cin.ignore();

The problem is in options- if you didn't call cin.ignore()after it, options will contain end of line and loop will continue...

问题在于options- 如果你没有cin.ignore()在它之后调用,选项将包含行尾并且循环将继续......

I hope this helps.

我希望这有帮助。

回答by Martin York

Don't do this:

不要这样做:

    while(myfile.good())
    {
        getline(myfile,inputLine);
        list.push(inputLine);
    }

The EOF flag is not set until you try and read past the EOF. The last full line read read up-to (bit not past) the EOF. So if you have have zero input left myfile.good() is true and the loop is enetered. You then try and read a line and it will fail but you still do the push.

在您尝试读取 EOF 之前,不会设置 EOF 标志。最后一整行读取读取(位未超过)EOF。因此,如果您的输入为零,则 myfile.good() 为 true 并且循环进入。然后你尝试阅读一行,它会失败,但你仍然在推动。

The standard way of reading all the lines in a file is:

读取文件中所有行的标准方法是:

    while(getline(myfile,inputLine))
    {
        list.push(inputLine);
    }

This way the loop is only entered if the file contained data.

这样,只有在文件包含数据时才进入循环。

Your other problem seems to stem from the fact that you have:

您的另一个问题似乎源于以下事实:

 std::getline(std::cin,task); // THIS is OK
 std::cin.ignore();           // You are ignoring the next character the user inputs.
                              // This probably means the next command number.
                              // This means that the next read of a number will fail
                              // This means that std::cin will go into a bad state
                              // This means no more input is actually read.

So just drop the cin.ignore() line and everything will work.

因此,只需删除 cin.ignore() 行,一切都会正常进行。

回答by Edward Strange

Instead of using ">>" directly on your stream you might consider using getline and then attempting to fetch your option from that. Yes, it's less "efficient" but efficiency isn't generally an issue in such situations.

您可能会考虑使用 getline,然后尝试从中获取您的选项,而不是直接在您的流上使用“>>”。是的,它的“效率”较低,但在这种情况下效率通常不是问题。

You see, the problem is that the user could enter something silly here. For example, they could enter something like "two", hit enter, and then your program is going to pitch a fit as it happily continues trying to decipher an empty option over and over and over and over again. The user's only recourse the way you have it set up (and the way those recommending use of ignore()are recommending) is to kill your program. A well behaved program doesn't respond in this way to bad input.

你看,问题是用户可能在这里输入一些愚蠢的东西。例如,他们可以输入诸如“二”之类的东西,按回车键,然后您的程序就会变得合适,因为它会高兴地一遍又一遍地尝试破译一个空选项。用户通过您设置它的方式(以及推荐使用的方式推荐的方式)的唯一追索权ignore()是终止您的程序。一个表现良好的程序不会以这种方式响应错误的输入。

Thus your best option is not to write brittle code that can seriously break down with the most modest of user ignorance/malfunction, but to write code that can handle error conditions gracefully. You can't do that by hoping the user enters a number and then a newline. Invariably, someday, you'll bet poorly.

因此,您最好的选择不是编写会因最轻微的用户无知/故障而严重崩溃的脆弱代码,而是编写可以优雅地处理错误情况的代码。你不能通过希望用户输入一个数字然后一个换行符来做到这一点。总有一天,你会下注很差。

So, you have two options to read your option. First, read a full line from the user, make sure the stream is still good, and then turn the string you get into a stream and try to read your integer out of it, making sure this other stream is still good. Second option, attempt to read a number, verify that the stream is still good, read a line and make sure the stream is still good and that your string is empty (or just ignore it if it isn't, your choice).

因此,您有两种选择来阅读您的选项。首先,从用户处读取整行,确保流仍然良好,然后将您获得的字符串转换为流并尝试从中读取整数,确保另一个流仍然良好。第二个选项,尝试读取一个数字,验证流是否仍然良好,读取一行并确保流仍然良好并且您的字符串为空(或者如果不是,则忽略它,您的选择)。

回答by Edward Strange

@Vladimir is right. Here is the mechanism behind the bug:

@Vladimir 是对的。这是错误背后的机制:

When you enter option '3', what you actually put into stream is "3\n". cin >> optionconsumes "3" and leaves "\n". getline()consumes "\n" and your call to ignore()after getline()waits for user input.

当您输入选项“3”时,您实际放入流中的是“3\n”。cin >> option消耗“3”并留下“\n”。getline()消耗 "\n" 和您的呼叫ignore()aftergetline()等待用户输入。

As you can see, teh sequence of events is already not what you expected.

如您所见,事件的顺序已经不是您所期望的。

Now, while ignore() is waiting for input, you type in your line. That line you're typing is what will go to "cin >> option.

现在,当 ignore() 等待输入时,您输入您的行。您输入的那一行是“cin >> 选项”的内容。

If you just give it one symbol, ignore() will dispose of it for you, and option will be read correctly. However, if you give it non-numeric symbols, stream will set failbit when trying to read the option. From that point on, your stream will refuse to do anything. Any << or getline will not set any new values in the variables they are supposed to change. You'll keep 3 in option and "" in task, in a tight loop.

如果你只给它一个符号,ignore() 会为你处理它,并且选项会被正确读取。但是,如果你给它非数字符号,流将在尝试读取选项时设置失败位。从那时起,您的流将拒绝做任何事情。任何 << 或 getline 都不会在它们应该更改的变量中设置任何新值。您将在选项中保留 3 并将任务中的 "" 保留在一个紧密的循环中。

Things to do:

要做的事情:

  • always check cin.eof(), cin.fail() and cin.bad().
  • always initialize your variables and declare them in the narrowest scope possible (declare option=0 right before it's read).
  • 始终检查 cin.eof()、cin.fail() 和 cin.bad()。
  • 始终初始化您的变量并在尽可能窄的范围内声明它们(在读取之前声明 option=0)。

回答by Cistoran

I just figured out a way to kind of hack through it, not the greatest but it works. Create a character array, and then accept input in the array, and then put everything into the array into the string.

我只是想出了一种方法来破解它,虽然不是最好的方法,但它确实有效。创建一个字符数组,然后接受数组中的输入,然后将数组中的所有内容放入字符串中。

char buff[256];
            cout << endl << "Enter the task that you would like to add:" << endl;
            cin >> task;
            task += " ";
            cin.getline(buff, 256);
            for(int i = 1; buff[i] != 0; i++){
                task += buff[i];
            }