c++将整数从 .txt 文件读入堆栈
这太愚蠢了。我已经被困了一个小时,试图读取由单个空格分隔的数字的 .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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,仔细看看这一行:
最终,您会注意到分号。编译器认为这意味着您想要一个不执行任何操作的循环(此处的分号表示单个空语句)。因此,循环读入所有数字,但对它们不执行任何操作。
下一部分被单独解释为它自己的范围内的一条语句(用大括号表示),在循环之后执行:
所做的就是将最后读取的数字压入堆栈,导致您认为循环只执行一次。
删除
;
就OK了!一旦被这个咬住,你就永远不会忘记;-)在一个不相关的注释中,将
argv[1]
(一个 C 风格的字符串)放入中有点愚蠢string
对象,然后使用c_str()
将其转回 ifstream 构造函数的 C 字符串。只需直接使用 argv[1] 即可,因为您没有用它做任何其他事情。另外,最好先检查 argc 并确保传入文件名。最后,您应该检查文件是否已成功打开,而不是假设它已成功打开 - 至少使用assert(myfile.is_open());
明确您的假设。哦,您根本不使用line
变量。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 astring
object, 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 checkargc
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 anassert(myfile.is_open());
. Oh, and you don't use theline
variable at all.