简体   繁体   English

c ++从.txt文件读取整数到堆栈

[英]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. 我一直被困在一个小时内试图读取一个由单个空格分隔的.txt文件。 The while loops only gets executed once for some reason! while循环只能由于某种原因执行一次!

#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. 在一个不相关的说明中,采用argv[1] (一个C风格的字符串),将它放入一个string对象,然后使用c_str()将其转换回ifstream构造函数的C字符串是有点傻。 Just use argv[1] directly, since you're not doing anything else with it. 只需直接使用argv[1] ,因为你没有做任何其他事情。 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()); 此外,最好首先检查argc并确保传入文件名。最后,您应检查文件是否已成功打开而不是假设 - 至少使用assert(myfile.is_open());明确表示您的假设assert(myfile.is_open()); . Oh, and you don't use the line variable at all. 哦,你根本不使用line变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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