从 .txt 文件中读入向量 C++
Reading into a vector from a .txt file c++
所以我需要制作一个充当虚拟词典的程序。虽然我不希望任何人为我编写我的代码,但我会很感激对我的代码的一些反馈,也许是在正确方向上寻找一些关于我遇到的问题的信息的观点。
我的大部分程序都运行良好,但我在从 .txt 文件填充矢量时遇到了问题,诚然,我并不真正理解它是如何工作的。
这是我一直在使用的:
ifstream myfile(filename);
if (myfile.is_open())
{
string Line;
string buffer;
string currentWordType = "none";
string currentWord = "none";
string currentWordDef = "none";
while (!myfile.eof())
getline(myfile, buffer);
currentWordType = buffer;
getline(myfile, buffer);
currentWord = buffer;
getline(myfile, buffer);
currentWordDef = buffer;
Word newWord(currentWordType, currentWord, currentWordDef);
wordList.push_back(newWord);
}
myfile.close();
再说一次,我并不是要找人帮我做这件事,只是可能会指出我在某些方面出了问题,并为我指明正确的方向。
谢谢!
有一个 while 循环你忘记了 {},在这个例子中它会 运行 只有下一行:
getline(myfile, buffer);
直到到达eof,也就是说每次都会覆盖。如果您可以修复代码,那么我们就知道这不是问题所在。你也可以 post 你到底得到了什么错误,或者你得到的输出是什么,这会有所帮助。
要从一行中读取三个字符串,每个字符串都需要一个循环...但不仅仅是检查 eof
while (!myfile.eof())
我们检查流的所有错误状态
while( myfile ){ ...
};
每次读取后我们应该检查是否成功...
std::string currentWordType;
if( ! getline(myfile, currentWordType)) {
break;
}
std::string currentWord;
if( ! getline(myfile, currentWord)) {
break;
}
std::string currentWordDef;
if( ! getline(myfile, currentWordDef)) {
break;
}
然后我们可以像以前一样将Word
添加到wordList
。
Word newWord(currentWordType, currentWord, currentWordDef);
wordList.push_back(newWord);
查看工作示例here
或者你可以在条件中解析
while( myfile >> currentWordType >> currentWord >> currentWordDef ) {
Word newWord(currentWordType, currentWord, currentWordDef);
wordList.push_back(newWord);
};
查看工作示例 here
所以我需要制作一个充当虚拟词典的程序。虽然我不希望任何人为我编写我的代码,但我会很感激对我的代码的一些反馈,也许是在正确方向上寻找一些关于我遇到的问题的信息的观点。
我的大部分程序都运行良好,但我在从 .txt 文件填充矢量时遇到了问题,诚然,我并不真正理解它是如何工作的。
这是我一直在使用的:
ifstream myfile(filename);
if (myfile.is_open())
{
string Line;
string buffer;
string currentWordType = "none";
string currentWord = "none";
string currentWordDef = "none";
while (!myfile.eof())
getline(myfile, buffer);
currentWordType = buffer;
getline(myfile, buffer);
currentWord = buffer;
getline(myfile, buffer);
currentWordDef = buffer;
Word newWord(currentWordType, currentWord, currentWordDef);
wordList.push_back(newWord);
}
myfile.close();
再说一次,我并不是要找人帮我做这件事,只是可能会指出我在某些方面出了问题,并为我指明正确的方向。
谢谢!
有一个 while 循环你忘记了 {},在这个例子中它会 运行 只有下一行:
getline(myfile, buffer);
直到到达eof,也就是说每次都会覆盖。如果您可以修复代码,那么我们就知道这不是问题所在。你也可以 post 你到底得到了什么错误,或者你得到的输出是什么,这会有所帮助。
要从一行中读取三个字符串,每个字符串都需要一个循环...但不仅仅是检查 eof
while (!myfile.eof())
我们检查流的所有错误状态
while( myfile ){ ...
};
每次读取后我们应该检查是否成功...
std::string currentWordType;
if( ! getline(myfile, currentWordType)) {
break;
}
std::string currentWord;
if( ! getline(myfile, currentWord)) {
break;
}
std::string currentWordDef;
if( ! getline(myfile, currentWordDef)) {
break;
}
然后我们可以像以前一样将Word
添加到wordList
。
Word newWord(currentWordType, currentWord, currentWordDef);
wordList.push_back(newWord);
查看工作示例here
或者你可以在条件中解析
while( myfile >> currentWordType >> currentWord >> currentWordDef ) {
Word newWord(currentWordType, currentWord, currentWordDef);
wordList.push_back(newWord);
};
查看工作示例 here