在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。有什么建议?谢谢!
答案 0 :(得分:3)
这是因为当您读取最后一行时,它不会设置eof位和失败位,只有当您读取 END 时,eof位才会被设置并且{{1} }返回true。
eof()
将其更改为
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;
}
答案 1 :(得分:0)
while (!inputStream.eof())
应该是
while (inputStream >> x)
答案 2 :(得分:-1)
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;