开发者

How do I make .getline get answers for every time through

开发者 https://www.devze.com 2023-04-13 04:58 出处:网络
I am a junior programmer, probably bad code which you computer experts can figure out. I have made this memorizing a paragraph program for my own use, can you figure 开发者_如何学Pythonout a way so th

I am a junior programmer, probably bad code which you computer experts can figure out. I have made this memorizing a paragraph program for my own use, can you figure 开发者_如何学Pythonout a way so that the getline happens every time throough? Here's my code...

#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");

}


Without going all the way through your code. It is probable that bytes are being left in the input buffer following a getline() call. I'll explain with ASCII art.

Say your buffer looks like this, where every empty box can hold a byte.

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

When you enter a phrase (like "FOO"), and press Enter, the buffer looks like this:

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

The '\n' character (the newline character) is added by the Enter key.

When getline() reads through the buffer, it reads until it hits the newline character, but it doesn't remove it. So, the call looks like:

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

The next call to getline() will read in the newline (and remove it from the buffer).

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

This behaviour has led to the common practise of "clearing the buffer" after reading from the input buffer. This can be achieved by doing

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

after each buffer read. It also helps to define that as a macro or inline function, to quickly call it any time.

0

精彩评论

暂无评论...
验证码 换一张
取 消