我正在尝试编写一个接受文件名和行号并从该特定行返回字符串的函数。问题是我的函数仅在读取文件的最后一行时返回一个字符串,而在读取其他行时则不返回任何字符串。
这是我的功能:(我的行参数从0开始,所以8实际上是第9行)
string txtRW_readline(string FileName,int Line){
ifstream fin;
fin.open(FileName.c_str());
string txtline;
for(int i = 0; i <= Line ; i++){
getline(fin,txtline);
cout << "Reading line: " << i << endl;
cout << "Result: " << txtline << endl << endl;
}
fin.close();
cout << "Returning: " << txtline << endl;
return txtline;
}
int main(){
cout << txtRW_readline("input.txt",8);
return 0;
}
这是我的input.txt:
A1
B2
C3
D4
E5
F6
G7
H8
I9
这是我的输出:(当cout << txtRW_readline(“ input.txt”,8)时)
Reading line: 0
Result: A1
Reading line: 1
Result: B2
Reading line: 2
Result: C3
Reading line: 3
Result: D4
Reading line: 4
Result: E5
Reading line: 5
Result: F6
Reading line: 6
Result: G8
Reading line: 7
Result: H8
Reading line: 8
Result: I9
Returning: I9
I9 <-- This one returns a line
这是我的输出:(当cout << txtRW_readline(“ input.txt”,7)时)
Reading line: 0
Result: A1
Reading line: 1
Result: B2
Reading line: 2
Result: C3
Reading line: 3
Result: D4
Reading line: 4
Result: E5
Reading line: 5
Result: F6
Reading line: 6
Result: G8
Reading line: 7
Result: H8
Returning: H8
<-- This one returns nothing -->
任何人都可以向我解释为什么会发生这种情况以及如何解决吗?