【问题标题】:How do I make .getline get answers for every time through我如何让 .getline 每次通过
【发布时间】:2011-10-16 23:53:07
【问题描述】:

我是一名初级程序员,可能是您计算机专家可以弄清楚的糟糕代码。我已经制作了这个记忆段落程序供我自己使用,你能想出一个方法让 getline 每次都发生吗?这是我的代码...

#include <iostream>
#include <string>
#include <Windows.h>

using namespace std;

void main(){
    string sentence;
    string attempt;
    char key;
    int counter = 0;

    cout << "Insert your sentence / paragraph (will be case sensitive) (don't press     enter until you're done)." << endl << endl;
    getline (cin, sentence);
    cout << endl;
    while (true){
        system ("cls");
        Sleep (5);
        cout << "Now enter the sentence / paragraph" << endl;
            getline (cin, attempt);
        if (sentence == attempt){
            cout << "Good job, do you want to go again? N for no, anything else for     yes" << endl;
            cin >> key;
            if (key == 'n' || key == 'N'){
                break;
            }
        }
        else{
            cout << "You messed up, try again." << endl;
            system("pause");
            continue;
        }
    }
    system("pause");

}

【问题讨论】:

标签: c++ getline


【解决方案1】:

无需遍历您的代码。在getline() 调用之后,字节可能会留在输入缓冲区中。我会用ASCII艺术来解释。

假设你的缓冲区看起来像这样,每个空盒子都可以容纳一个字节。

|_|_|_|_|_|...|_|

当您输入一个短语(如“FOO”)并按 Enter 键时,缓冲区如下所示:

|F|O|O|\n|_||_|...|_|

'\n' 字符(换行符)由 Enter 键添加。

getline() 读取缓冲区时,它会一直读取直到遇到换行符,但不会删除它。所以,调用看起来像:

getline(cin, str) // = "FOO"
|\n|_|_|...|_| // buffer after call

getline() 的下一次调用将读取换行符(并将其从缓冲区中删除)。

getline(cin, str) // = "\n"
|_|_|_|_|_|...|_| // buffer after call

这种行为导致了从输入缓冲区读取后“清除缓冲区”的常见做法。这可以通过这样做来实现

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

在每次缓冲区读取之后。它还有助于将其定义为宏或内联函数,以便随时快速调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多