2013-07-28 23 views
0

我有一个功能,通过文字需要从文件输入,字符:在文件重置之前,最后一个字符是如何接受两次?

#include <iostream> 
#include <fstream> 

using namespace std; 

ifstream input("sequence.txt"); 

char getChar(){ 
char nextType; 
if (input.eof()) { 
    input.clear(); 
    input.seekg(0,ios::beg); 
}  
input >> nextType; 
return nextType; 
} 

int main(){ 
for(int i = 0; i < 10; i++){ 
    cout << getChar() << endl; 
} 
return 0; 
} 

内部“sequence.txt”输入为:

I O 

所以输出应打印交替的我和O的,而是输出:

I O O I O O I O O I 

如何在第一次读取文件中的最后一个字符后重置文件?

回答

2

eof仅当您在到达文件结尾后尝试读取时才设置。相反,首先尝试读取char。如果失败,则重置流,然后再试一次,这样的:

char getChar() 
{ 
    char nextType; 
    if (!(input >> nextType)) 
    { 
     input.clear(); 
     input.seekg(0,ios::beg); 
     input >> nextType; 
    } 
    return nextType; 
} 
+0

谢谢!我从未考虑过这种方法。我很感激帮助。 –

+0

即使这是不正确的。您无法验证第二次读取是否成功。考虑如果文件是空的,或者只包含空格,会发生什么。 –

+0

@JamesKanze:我是在问题中提出的前提条件下运作的。额外的信息很好,但我认为对实际问题的答案仅仅是解释eof如何工作以及如何避免这种行为。 –

0

你无需测试输入 是否成功返回一个值。你在功能应该是alont行的 :

char 
getChar() 
{ 
    char results; 
    input >> results; 
    if (!input) { 
     input.clear(); 
     input.seekg(0, std::ios_base:;beg); 
     input >> results; 
     if (!input) { 
      // There are no non-blanks in the input, so there's no way we're 
      // going to read one. Give up, generating some error condition 
      // (Throw an exception?) 
     } 
    } 
    return results; 
} 

重要的是,有没有执行其中 读取或拷贝results的路径,而不在成功地读取 它。 (除非你另外指派什么东西。你 可能,例如,与'\0'初始化,与 约定该函数返回'\0'如果无法 读什么。)

我想补充一点input.eof()的测试仅在之后确定输入失败,才有效 。即使没有更多有效的输入,我也可能会返回错误 。

相关问题