提问者:小点点

永不结束的文件读取循环(C++)


我写的一些代码应该读取文本文件中的所有新行,但它在运行的循环中被卡住了。

代码如下:

#define MAX_MESSAGE_LENGTH 200;

fstream("some/random/file.txt", ios::in | ios::out);
streampos fileSizeReference = 0;

vector<string> messages;
vector<string> onDisplay;

char message[MAX_MESSAGE_LENGTH];
if((int)fileSizeReference == 0)
    fileReader.seekg(0);
            
else
    fileReader.seekg((int)fileSizeReference + 1);
            
cout << "Test" << endl;
            
// Add all new messages to the messages vector
do
{
    fileReader.getline(message, MAX_MESSAGE_LENGTH);
    string newMsg = message;
    messages.push_back(newMsg.substr(0, MAX_MESSAGE_LENGTH));
}
while (!fileReader.eof());
//

cout << "Test" << endl;
            
fileReader.seekg(0, ios::beg);
            
// Set the newest messages in the onDisplay vector
for(int i = 0; i < amountOfMessages; i++)
{
    onDisplay[i] = messages[messages.size() - (i + 1)];
}
//
            
cout << "Test" << endl;
        
// Display new messages
int current_Y = 0;
        
for(int i = 0; i < amountOfMessages; i++)
{
    current_Y = renderText(messages[i], current_Y);
}
//
        
// set the new file size as the fileSizeReference
fileReader.seekg(0, ios::end);
fileSizeReference = fileReader.tellg();

文本文件如下所示:

Hello World!
Carpe Diem
Random Message

每当我运行这段代码时,我都不会通过第一个do-while循环。 这是第一次运行,因此fileSizeReference为0。

循环中的newMsg变量始终是空字符串,就像消息数组一样。

你们有谁知道为什么我的代码被卡住了吗? 提前谢谢你!


共1个答案

匿名用户

您至少有两个错误。

do
{
    fileReader.getline(message, MAX_MESSAGE_LENGTH);
    string newMsg = message;
    messages.push_back(newMsg.substr(0, MAX_MESSAGE_LENGTH));
}
while (!fileReader.eof());

应该是

while (fileReader.getline(message, MAX_MESSAGE_LENGTH))
{
    string newMsg = message;
    messages.push_back(newMsg.substr(0, MAX_MESSAGE_LENGTH));
}

更多阅读为什么IOStream::EOF在循环条件中(即`while(!stream.eof())`)被认为是错误的?

顺便提一下,while循环中的这两行也可以简化,这将非常好地工作。

    messages.push_back(message);

其次,在完成读取之后,流将处于错误状态,您需要清除该状态,然后返回到文件的开头(关闭和重新打开文件也可以)。

while (fileReader.getline(message, MAX_MESSAGE_LENGTH))
{
    string newMsg = message;
    messages.push_back(newMsg.substr(0, MAX_MESSAGE_LENGTH));
}
fileReader.clear();
fileReader.seekg(0, ios::beg);

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(永不|结束|文件|读取|循环|c++)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?