Can't really understand what cin.ignore() does

Hello and thank you in advance for your time.
I was reading some old code I wrote to improve it and when it came to one line I had no idea why I wrote that and I asked a skilled programmer but sadly he never uses this kind of stuff. I also searched the internet but not being very skilled I didn't really understand most of what I read. So here's the code, and my question simply is, why did I use cin.ignore() before returning -1 in case of an error ? (last line) Thanks !

1
2
3
4
5
6
7
8
9
10
11
12
      //Opening files, closing the program if they can't be opened
    bool err=0;
    ifstream settings;
    settings.open("settings.txt", ios::in);
    if (!settings) {cerr << "settings.txt cannot be opened!" << endl; err=1;}
    ifstream input;
    input.open("input.txt", ios::in);
    if (!input) {cerr << "input.txt cannot be opened!" << endl; err=1;}
    ofstream output;
    output.open("output.txt", ios::out);
    if (!output) {cerr << "output.txt cannot be opened!" << endl; err=1;}
    if (err) {cin.ignore(); return -1;}
std::istream::ignore() (std::cin is an istream object) is used to purge any remaining characters from the stream's internal buffer. You may pass two parameters, the first being the number (let's call it n) of characters to remove, and the second being a delimiting character. The method will continue discarding characters until it finds the delimiting character or until n characters are extracted.
If you pass no parameters, by default, you will remove one character from the buffer, and the delimiting character is EOF (end-of-file).

std::cin.ignore() is often called in conjunction with other methods like std::cin.clear() (which sets the stream objects internal error state flags, and resets them by default) after reading invalid input.

If this is all of your code, then there isn't any reason to discard characters from std::cin's buffer, since it hasn't even been used. What you probably meant to write was std::cin.get() (which is essentially the same as calling std::cin.ignore() without any parameters), which waits to receive some data from the user before proceeding - in this way, it can be used to pause the program, which enables your user to read any potential error messages before the program terminates. Otherwise, the program would terminate before the user has a chance to read any of your errors.
Last edited on
First of all, thank you for your help. And yes, now I remember that I put it in order to let the user actually read the error without having the dialog box immediately close. But I wasn't able to see that because I wasn't testing the final product, so it didn't directly close the dialog box anyway.
Have a good day.
Topic archived. No new replies allowed.