Hey guys I've trouble understanding (inFile >> ch).get();. After I added this piece of code, it start working. I found the solution on the Internet but I really want to know what's happening right there.
User is supposed to enter a specific text file which contains some names and the amount of money they donated. Textfile is down below
The >> operator does two things. First, it extracts data from and input stream ( cin is such a stream ), and then it returns the stream.
The extraction first ignores all white space. It then reads data until a character is found that is not of the type it is looking for. That character is not extracted.
The stream is returned, which allows for chaining: cin >> x >> endl;
The return also means you can do what is in your code, specifically call get() with the stream that is returned from cin >> num.
The reason for this is that the >> operator has left the new line character in the stream buffer, and this needs to be ignored.
The extraction first ignores all white space. It then reads data until a character is found that is not of the type it is looking for. That character is not extracted.
So, is it a "new line" in the text document that's messing the whole thing up? And when I'm adding .get() it "takes care" of the "new line".
Correct me if I'm wrong...
i dont understand why you would use it, but im assuming operator>> for ifstream returns an ifstream, giving access to the .get member
If there are other ways to solve this, I'm up for suggestions! :]
So, is it a "new line" in the text document that's messing the whole thing up? And when I'm adding .get() it "takes care" of the "new line".
Basically.
The issue with the new line is the use of the function getline(). By default, getline() extracts characters up until ( and including ) a newline character. Since the >> operator doesn't extract a trailing newline, a call to getline() after >> will create an empty string.
The preferred method is to use ignore() after using a >> operator:
1 2 3
int x;
cin >> x;
cin.ignore( 80, '\n' ); // ignore until 80 characters have been ignored, or a newline has been extracted