【发布时间】:2013-11-06 01:03:31
【问题描述】:
我的 C++ 项目的目的是输出一个包含由简单字符组成的图片的文件。
我的项目的第一部分要求我“包含一个从输入文件读取命令并返回表示所读取命令的整数值的函数”。那是我的 takeCommand 函数。看起来效率极低,但如果我理解正确的话,我想这是必要的。
当前的问题是我的 main 函数中的 while 循环运行一个无限循环。输出文本“Works”时,它会不断重复。我的意图是制作一个文件结束控制循环。在takeCommand函数内部,当读取到最后一行时,takeCommand函数停止运行,while循环结束。
我需要关于如何让 while 循环工作而不不断重复的想法。
我目前拥有的是:
int takeCommand(int& num, int& cmd);
ifstream infile;
ofstream outfile;
int main()
{
const int MAX_FOR = 3;
string str;
int num, cmd;
infile.open("DrawingInput_01.txt");
outfile.open("DrawingOutput_01.txt");
for (int i = 0; i < MAX_FOR; i++)
{
getline(infile,str);
}
takeCommand(num,cmd);
while(infile)
{
cout << "Works";
/*switch(cmd)
{
case '1': printSpace(infile, outfile); break;
case '2': printChar(infile, outfile); break;
case '3': printNewline(infile, outfile); break;
case '0': break;
}*/
takeCommand(num, cmd);
}
infile.close();
outfile.close();
return 0;
}
int takeCommand(int& num, int& cmd)
{
string str;
char firstChar;
infile.open("DrawingInput_01.txt");
for (int i = 0; i < 3; i++)
{
getline(infile.str);
}
infile >> firstChar >> str >> num;
switch(firstChar)
{
case 's': cmd = 1; break;
case 'p': cmd = 2; break;
case 'n': cmd = 3; break;
case 'q': cmd = 0; break;
}
return cmd;
}
其中一个输入文件如下所示:
; CS 1044 Fall 2010
; Project 4
; Basic Cat
space 1
print 1 /
print 1 \
print 1 _
print 1 /
print 1 \
newline
print 1 (
space 1
print 1 o
print 1 .
print 1 o
space 1
print 1 )
newline
space 1
print 1 >
space 1
print 1 ^
space 1
print 1 <
newline
quit
输出文件应该是兔子。
void 函数在我的代码中,现在不是问题。
【问题讨论】:
-
从
takeCommand中丢失infile.open()和getlines()- 文件流已经打开并且在main()中跳过了这些行。然后,使用if (infile >> firstChar >> str >> num) { ... } else { std::cerr << "unexpected EOF\n"; exit(1); },以便在尝试使用变量之前检查变量是否被正确读取。 -
我认为您实际上并没有从 infile 中获取任何内容。有关类似问题,请参阅 this question。
标签: c++ stream while-loop pass-by-reference infinite-loop