我想逐行读取文件,这里是代码:
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/