首页 > 解决方案 > 如何在 C++ 中将文本文件读入向量?

问题描述

我正在尝试将包含 9 行单个整数的文本文件读入向量中。VS Code 没有返回语法错误,但是当我调试程序时,我在 main 下遇到了分段错误(我在特定行上发表了评论)。我的实施有问题吗?先感谢您!

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
vector <int> list = {};

int count_line(){   //Count the number of accounts in the txt file
    int count = 0;
    string line;
    ifstream count_file;
    count_file.open("text.txt"); //The text file simply have 9 lines of single integers in it
    if (!count_file){
        cerr<<"Problem reading from file"<<endl;
        return 1;
    }
    while (!count_file.eof()){
        getline(count_file,line);
        count ++;
    }
    count_file.close();
    return count - 1;
}

int main(){
    int i{0};
    count_line();
    ifstream input {"text.txt"};
    if (!input){
        cout<<"Problem reading from file"<<endl;
        return 1;
    }
    while (i <= count_line() && count_line() > 0){
        input>>list[i]; //I am getting a segmentation fault error here
        i++;
    }
    for (int k = 0; k < 9 ; k++){
        cout<<list[k];
    }
}

标签: c++vectorfstream

解决方案


这个向量:

vector <int> list = {};

正好有零个成员。您永远不会尝试增加其大小,因此对该数组的任何访问都会导致错误的结果。

有几个地方可以访问此向量:

input>>list[i];

// and

cout<<list[k];

这些都是对列表的无效访问。

要解决此问题,您可以将数据读入一个值,然后将其附加到向量中:

int value;
input >> value;
list.emplace_back(value); // emplace back expands the vector by one place.

但这不是你唯一的问题:

 while (i <= count_line() && count_line() > 0){

此 while 语句包含对打开文件的调用解析整个文件并返回计数。我怀疑编译器可以优化它,所以这是非常昂贵的调用。

您可以只读取值直到没有剩余吗?

 int   value;
 while(input >> value) {
     list.emplace_back(value);
 }

但正确的方法是:

 #include <vector>
 #include <iterator>
 #include <iostream>
 #include <fstream>

 int main()
 {
     std::ifstream     file("text.txt");
     std::vector<int>  data(std::istream_iterator<int>{file},
                            std::istream_iterator<int>{});

     for(auto val: data) {
         std::cout << val << " ";
     }
     std::cout << "\n";
 }

推荐阅读