【问题标题】:How can I put elements of a file into a list?如何将文件的元素放入列表中?
【发布时间】: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_iteratorstd::back_inserter 一起使用来完全消除循环,例如:How do I get an input file to read into a string array in C++?

标签: c++ list file


【解决方案1】:

基本上是对的。你只需要重新排列你的循环看起来像这样:

std::string line;
std::list<std::string> l;

//read first file
std::ifstream myfile ("Dataset.1.02.txt");
if (myfile.is_open()){
    if (getline(myfile, line)) {
        do {
            l.push_back(line);
        } while(getline(myfile, line));
    }
    myfile.close();
}

for (auto v : l){
    std::cout << v << "\n";
}

if 处理文件为空的情况。然后,一旦我们有了一行,我们就将一行放入列表中并尝试读取下一行。如果我们没有读到一行,我们就完成了。

【讨论】:

  • 很高兴听到这个消息!如果它解决了您的问题,请检查左侧的复选标记。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
相关资源
最近更新 更多