【发布时间】:2014-10-14 17:57:22
【问题描述】:
我正在开发一个函数,它读取文件的行,直到文件中到达“XXX”行,并且计数器会跟踪已读取的行数。然后程序计算文件中剩余的行数。我正在使用 if 语句来确定何时中断 while 循环(当读取的行等于“XXX”时)并且不满足条件。即使当 line == "XXX" 时,else 语句仍然会运行。我的代码有什么问题?谢谢!
#include <string>
#include <iostream>
#include <fstream>
using std::string;
using std::endl;
using std::cout;
using std::ifstream;
int main()
{
//Main function
}
void read_file(string input_file_name)
{
string i_filename = input_file_name;
ifstream infile;
infile.open (i_filename);
string line;
int num_of_terms1 = 0;
int num_of_terms2 = 0;
if (!infile)
{
cout << "Your input file could not be opened."<<endl;
}
else
{
while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
if (line == "XXX")
{
break;
}
else
{
cout << line << endl;
num_of_terms1++;
}
}
while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
num_of_terms2++;
}
}
cout << "Terms 1: "<<num_of_terms1 <<endl;
cout << "Terms 2: "<< num_of_terms2 <<endl;
infile.close();
}
这是一个示例输入文件,inputfile.txt:
-2 3
4 2
XXX
-2 3
提前感谢您的帮助!
【问题讨论】:
-
输出是什么样子的?
-
你为什么不做一些调试。首先在循环的每次迭代中检查
line的值。您真正的问题不是程序无法运行,而是您还没有学会如何调试。一旦你这样做了,你就可以自己解决所有这些问题。 -
为什么你认为“即使 line == "XXX",else 语句仍然会运行”?
-
你检查过空格、车厢等吗?
-
while (!infile.eof())相关:Why is iostream::eof inside a loop condition considered wrong?
标签: c++ string if-statement compare