2013-10-15 57 views
0

在C++中,我试图读取文件并将该文件中的字符串存储到程序中的字符串中。这很好,直到我得到最后一个字,总是存储两次。相同的单词添加两次

ifstream inputStream; 
string next = ""; 
string allMsg = ""; 
inputStream.open(fileName.c_str()); 
string x; 

while (!inputStream.eof()) 
{ 
    inputStream >> x; 
    next = next + " " + x; 
} 
cout << "The entire message, unparsed, is: " << next << endl; 

这样做会增加最后一个字或int从我打开的文件到下一个。有什么建议么?谢谢!

+3

['而(!EOF())'是错误的。(http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside -a-loop-condition-considered-wrong) – chris

回答

3

这是因为当你读到最后一行,也不会置EOF位和故障位,只有当你阅读END,EOF位设置和eof()返回true。

while (!inputStream.eof()) // at the eof, but eof() is still false 
{ 
    inputStream >> x; // this fails and you are using the last x 
    next = next + " " + x; 
} 

将其更改为

while(inputStream >> x){ 
    // inputStream >> x; dont call this again! 
    next = next + " " + x; 
} 
+0

这不起作用,因为它现在只在每隔一个字中读取。因此,如果文件中提到“一二三四”,现在只存储“一三五”到下一个。 – robertjskelton

+0

你不要调用'inputStream >> x;'循环内部... –

0
while (!inputStream.eof()) 

应该

while (inputStream >> x) 
+0

@ZacHowlandx为什么?... – 0x499602D2

+0

@ 0x499602D2 - 已经被很多次的回答了:http://stackoverflow.com/questions/5605125/why-is-iostreameof-循环内条件考虑错误 –

-1

EOF()如果最后读取命中文件的结尾,如果没有下一个读将达到文件的末尾将返回true。尝试:

ifstream inputStream; 
string next = ""; 
string allMsg = ""; 
inputStream.open(fileName.c_str()); 
string x; 

inputStream >> x; 
if(!inputStream.eof()) { 
    do { 
     next = next + " " + x; 
     inputStream >> x; 
    } while (!inputStream.eof()) 
} 
cout << "The entire message, unparsed, is: " << next << endl; 
+0

这不应该被接受的答案。 Zac牧马人的准确和更完整。这是错误的。 –

相关问题