【发布时间】:2023-03-21 15:06:01
【问题描述】:
我正在调查,但没有找到很多信息。现在我对如何将文件的元素放入列表以及如何打印列表感到困惑。
std::string line;
std::list<string> l;
//read first file
ifstream myfile("Dataset.1.02.txt");
if (myfile.is_open()) {
getline(myfile, line);
while (getline(myfile, line) /**/) {
l.push_back(line);
}
myfile.close();
}
for (auto v : l) {
std::cout << v << "\n";
}
【问题讨论】:
-
删除
getline(myfile, line);之前的while(getline(myfile,line)/**/){代码对我来说看起来不错。 -
如果您有问题,可能是您放置文本文件的文件夹位置不正确。
-
考虑通过将
std::copy()与std::istream_iterator和std::back_inserter一起使用来完全消除循环,例如:How do I get an input file to read into a string array in C++?。