逐行读取文件,但出现问题的方法

问题描述

| 我想逐行读取文件,这是代码
map<int,string>WordList ; //int is the key,string the returnad value
int GetWordList(char* file)
{
    WordList.clear();
    char getch;
    int wordindex=-1;
    string tempstring=\"\";
    ifstream myFile(file);
    while (!myFile.eof())
    {
         myFile.get(getch);
         if (getch==\'\\r\') continue; // skipping \'\\r\' characters
         if (getch == \'\\n\' || myFile.eof() )
         {
               WordList[++wordindex]=tempstring;
               tempstring=\"\";
         }else  tempstring+=getch;
    }
    return wordindex; //returns the maximum index
}
我打电话了
 int totalStudents = GetWordList(\"C:\\Students.txt\");
文件中有三行内容, 但是当我运行程序时,它不会从while循环中退出,而且WordList始终为0,     

解决方法

        再来一遍:不要针对
eof
进行测试。 接下来,如果您始终只想一行阅读,为什么还要使循环如此复杂?那是三英镑。围绕它建立循环,就可以了。     ,        假设您使用连续整数作为索引,似乎没有什么理由使用
std::map<int,string>
而不是just5ѭ。 同样,将输入解析为行的代码似乎无法完成
std::getline
还不能很好完成的工作。 最后,您对文件结尾的测试不是很正确。将它们放在一起,您会得到类似的东西。
std::vector<std::string> lines;

std::string line;
std::ifstream myFile(filename);

while (std::getline(myFile,line))
    lines.push_back(line);
您可能还希望查看上一个问题的一些答案。     ,        不要忘记转义反斜杠:
GetWordList(\"C:\\\\Students.txt\");