简体   繁体   中英

c++ Reading in integers from a .txt file to a stack

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:

while (myfile >> num);

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:

{
    x.push(num);
}

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 a string object, then use c_str() to turn that back into a C-string for the ifstream constructor. Just use argv[1] directly, since you're not doing anything else with it. Also, it would be a good idea to check argc first 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 an assert(myfile.is_open()); . Oh, and you don't use the line variable at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM