逆向字问题 - 程序卡在输入循环中?
我正在尝试解决逆向单词问题。我的解决方案有效,甚至可以跳过空白行。然而,在读取文件的所有行后,程序会陷入循环,不断接受输入。这非常令人费解,我觉得这与我的外部 while 循环有关,但我看不出它有什么问题。
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
int main(int argc, char** argv)
{
stack<string> s;
ifstream in;
in.open(argv[1]);
do
{
do
{
string t;
in >> t;
s.push(t);
} while(in.peek() != '\n');
do
{
cout << s.top();
s.pop();
if(s.size() > 0) cout << " ";
else cout << endl;
} while(s.size() > 0);
} while(in.peek() != -1 || in.fail() || in.eof() || in.bad() );
in.close();
return 0;
}
I am trying to solve the reverse word problem. My solution works, and even skips blank lines. However, after all the lines of a file are read, the program gets stuck in a loop, constantly accepting input. This is very puzzling, and I feel like it has to do with my outer while loop, but I can't see what's wrong with it.
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
int main(int argc, char** argv)
{
stack<string> s;
ifstream in;
in.open(argv[1]);
do
{
do
{
string t;
in >> t;
s.push(t);
} while(in.peek() != '\n');
do
{
cout << s.top();
s.pop();
if(s.size() > 0) cout << " ";
else cout << endl;
} while(s.size() > 0);
} while(in.peek() != -1 || in.fail() || in.eof() || in.bad() );
in.close();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
问题出在内部循环上。如果我给出一个文本文件,其中一行仅包含一个单词,它将失败,因为它永远不会从内部循环中出来。
该代码对我有用:
Sriram
The problem is the inner loop. If I give in a text file containing only one word on a single line, it will fail since it will never come out of the inner loop.
This code works for me:
Sriram
这是一种可能有效的方法。
Here is an approach that may work.
最后一个条件应该是
while(in)
。The last condition should just be
while(in)
.尝试使用
while(in >> t) {...}
Try using
while(in >> t) {...}
这:
肯定应该是:
或者,更好的是,只需测试流:
而且我认为 -1 实际上应该是 EOF。
This:
should surely be:
Alternatively, and better, just test the stream:
And I think that -1 should actually be EOF.