c++ - 一种逐行读取文件的方法,但会出现问题

标签 c++

我想逐行读取文件,这里是代码:

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,

最佳答案

鉴于您使用连续的整数作为索引,似乎没有理由使用 std::map<int, string>而不仅仅是 std::vector<std::string> .

同样,您将输入解析为行的代码似乎对 std::getline 的作用不大也不能做得很好。

最后,您对文件结尾的测试并不正确。将它们放在一起,您会得到类似的东西。

std::vector<std::string> lines;

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

while (std::getline(myFile, line))
    lines.push_back(line);

您可能还想查看 previous question 的一些答案.

关于c++ - 一种逐行读取文件的方法,但会出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6320737/

相关文章:

c++ - `is_trivially_destructible` 不适用于继承类

c++ - 在基于范围的 for 循环期间插入到 std::list 的后面

c++ - 如何从保存 RGBA 格式图像的缓冲区在 opencv 中创建图像

c++ - va_start 作为数组

c++ - STL max_element 未使用我的类中的重载运算符 operator<

c++ - 错误: passing 'const S' as 'this' argument discards qualifiers

c++ - 通过非智能指针参数将智能指针传递给函数

c++ - linux获取当前目录下文件信息的方法

c++ - 不能在函数调用中使用 int 后递减

c++ - 如何创建 typedef 结构的前向声明