Hey guys, I'm new to C++ and have an assignment for class where I need to read in words from a text file, but I can't get it to work. The instructor said after you open the file and do cin, it'll just take input from the file, but my program is still waiting for me to input it instead of the file.
That's what I have to test it, but it'll only take my input and not from file. Everything worked before when I used .get() and .getline() except it didn't ignore the white space, so my instructor said I have to use cin as it will ignore whitespace and only take in words from the file.
What am I doing wrong? This worked with my previous program where I didn't have to open the file but instead just added a command line argument with the text file name, but I can't do that this time as the file name is stored in a variable.
No, first I have to read in a file that's a grocery list, put the ingredients and inventory in an array, and then read in another text file of the same format, but this time its a list of inventory. Thirdly, I have to write out into a new file to determine how much of what I need to buy once the inventory is deducted from the grocery list. But I'm having trouble with it reading in everything... That's just a test code to see if it can read everything in the file.
I also tried a while loop that said:
while (!input_data.eof()){
}
instead of the size != 20 loop, but when I did the eof loop, it just kept printing 1's infinitely for some reason...
Ya eof is trouble as a while condition for reading in a file. So many other things can go wrong that don't involve the stream reaching the end of the file. You can use input_data.good() instead. This way, the loop will break if anything goes wrong.
Actually you can use a combination of the extraction operator with getline(). Something like this:
1 2 3 4 5 6 7
int num;
string s;
while( input_data.good() ) {
inFile >> num >> ws;
getline( inFile, s );
// do something with num and s
}
ws is a stream manipulator that eats whitespace, it's there because the extraction operator leaves whitespace in the stream.