我想阅读2个单独文件的第一行,然后比较它们......以下是我使用的代码,但它给了我“istream to string error”。我是否需要使用while条件才能开始先读取文件?
ifstream data_real(filename.c_str()); /*input streams to check if the flight info
are the same*/
ifstream data_test("output_check.txt");
string read1, read2;
string first_line_input = getline(is,read1);
string first_line_output_test = getline(data_test,read2);
string test_string1, test_string2;
int num_lines_output_test, num_lines_input;
if((first_line_input.substr(0,3)==first_line_output_test.substr(0,3)))
{
while(!data_test.eof()) // count the number of lines for the output test file with the first flight info
{
getline(data_test,test_string1);
num_lines_output_test++;
}
while(getline(is,test_string2)) // count the number of lines for the output test file with the first flight info
{
if(test_string2.substr(0,3)!="ACM")
num_lines_input++;
else
break;
}
}
答案 0 :(得分:1)
getline(istream, string)
返回对istream的引用,而不是字符串。
因此,比较每个文件的第一行可能是:
string read1, read2;
if !(getline(is,read1) && getline(data_test,read2)){
// Reading failed
// TODO: Handle and/or report error
}
else{
if(read1.substr(0,3) == read2.substr(0,3)){
//...
另外:永远不要使用eof()作为流读取循环的终止条件。写它的惯用方法是:
while(getline(data_test,test_string1)) // count the number of lines for the output test file with the first flight info
{
num_lines_output_test++;
}
答案 1 :(得分:0)
尝试添加此辅助函数:
std::string next_line(std::istream& is) {
std::string result;
if (!std::getline(is, result)) {
throw std::ios::failure("Failed to read a required line");
}
return result;
}
现在你可以按照你想要的方式使用文件中的行(即初始化字符串,而不是修改它们):
string first_line_input = next_line(is);
string first_line_output_test = next_line(data_test);