c++ - 如何将文件的元素放入列表中?

标签 c++ list file

我正在调查,但没有找到很多信息。现在我对如何将文件的元素放入列表以及如何打印列表感到困惑。

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";
}

最佳答案

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

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 处理文件为空的情况。然后,一旦我们有了一行,我们就将一行放入列表中并尝试读取下一行。如果我们未能读取一行,我们就完成了。

关于c++ - 如何将文件的元素放入列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905672/

相关文章:

python - 'for x in list:' 和 'for x in list[:]:' 有什么区别

java - 无法正确比较两个字符串

c# - 来自 Dapper Query 的简单字符串列表

file - ffmpeg 在编码/调整多个视频大小时保留文件创建和修改日期

C++静态初始化顺序惨败发生在什么时候?

c++ - 在紧密循环中使用 cin.get()

c++ - 无法使用 Code::Blocks 编译 wxWidgets

c++ - QTextEdit::setPalette 不更新文本颜色

c - select() 不等待

java - 通过代码编辑Linux网络配置文件("/etc/network/interfaces")