This is so stupid. I’ve been stuck literally for an hour trying to read in a .txt file of numbers that are separated by a single whitespace. The while loops only gets executed once for some reason!
#include <iostream>
#include <string>
#include <fstream>
#include <stack>
using namespace std;
int main(int argc, char* argv[])
{
string line;
string str(argv[1]);
ifstream myfile((str).c_str());
int num;
stack<int> x;
while (myfile >> num);
{
x.push(num);
}
return(0);
}
Hmm, look at this line more closely:
Eventually, you’ll notice the semi-colon. The compiler thinks this means you want a loop that does nothing (the semi-colon here indicates a single, empty statement). So, the loop reads in all the numbers, but does nothing with them.
The next section is interpreted separately as a statement in its own scope (denoted by the braces), to be executed after the loop:
All that does is push the last number read onto the stack, leading you to think the loop only executes once.
Remove the
;and you’re OK! Once bitten by this, you’ll never forget 😉On an unrelated note, it’s a bit silly to take
argv[1](a C-style string), put it into astringobject, then usec_str()to turn that back into a C-string for the ifstream constructor. Just useargv[1]directly, since you’re not doing anything else with it. Also, it would be a good idea to checkargcfirst and make sure that a filename was passed in. Finally, you should check that the file was successfully opened instead of assuming it — at the very least make your assumption explicit with anassert(myfile.is_open());. Oh, and you don’t use thelinevariable at all.