c++将整数从 .txt 文件读入堆栈

发布于 2024-12-28 04:55:48 字数 451 浏览 1 评论 0原文

这太愚蠢了。我已经被困了一个小时,试图读取由单个空格分隔的数字的 .txt 文件。由于某种原因,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);
}

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);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伊面 2025-01-04 04:55:48

嗯,仔细看看这一行:

while (myfile >> num);

最终,您会注意到分号。编译器认为这意味着您想要一个不执行任何操作的循环(此处的分号表示单个空语句)。因此,循环读入所有数字,但对它们不执行任何操作。

下一部分被单独解释为它自己的范围内的一条语句(用大括号表示),在循环之后执行:

{
    x.push(num);
}

所做的就是将最后读取的数字压入堆栈,导致您认为循环只执行一次。

删除 ; 就OK了!一旦被这个咬住,你就永远不会忘记;-)

在一个不相关的注释中,将 argv[1] (一个 C 风格的字符串)放入 中有点愚蠢string 对象,然后使用 c_str() 将其转回 ifstream 构造函数的 C 字符串。只需直接使用 argv[1] 即可,因为您没有用它做任何其他事情。另外,最好先检查 argc 并确保传入文件名。最后,您应该检查文件是否已成功打开,而不是假设它已成功打开 - 至少使用 assert(myfile.is_open()); 明确您的假设。哦,您根本不使用 line 变量。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文