Jon Rurka
Jon Rurka

Reputation: 79

skipping cin.get() and cin.ignore()

For some reason, my program is skipping the code fragments cin.get(); and cin.ignore();. I do not know why this is happening, because the two fragments work fine when just inside the main() scope, and not in the if statement.

Here is the relevent code fragment:

input.open(inputFileName);
if (input.fail())
{
    cout << "Error: failed to open '" << inputFileName << "'.\n\n";
    cout << "Press '' to end the program...";
    cin.get(); //cin.ignore() also does nothing.
    input.close();
    exit(1);
}

The rest of the source code can be found here: http://pastebin.com/xy0qMvBq

Upvotes: 3

Views: 2883

Answers (3)

patrick ahrens
patrick ahrens

Reputation: 31

try:

std::string dummy;
getline(std::cin,dummy);

or (if you didnt allready):

cin.ignore(1000,'\n'); 

cin.ignore(1000,'\n'); removes all characters in the cin buffer, until it finds a '\n' character in the cin buffer or reaches the maximum of ignored/removed characters (1000 in this case).

Upvotes: 0

Aadil Imran
Aadil Imran

Reputation: 115

The part of the code posted by you is absolutely working fine and cin.get() is not bieng ignored in this case.

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

cin >> inputFileName;

With that command, the user is going to type some "stuff", and then hit enter. That's going to put the "stuff", plus a newline character into the input buffer. Then the "stuff" is going to get stored into inputFileName, and the newline character is going to be left there. This is what cin.get() and cin.ignore() read, they are not being skipped.

Upvotes: 3

Related Questions