简体   繁体   中英

How do you read a text file into a vector in c++?

I am trying to read a text file containing 9 lines of single integers into a vector. VS Code returns no syntax error but when I debug the program, I got a segmentation fault under main(I commented on the specific line). Am I doing something wrong with my implementation? Thank you in advance!

#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];
    }
}

You must allocate elements before using them.

one of fix:

    while (i <= count_line() && count_line() > 0){
        if (list.size() <= (size_t)i) list.resize(i + 1); // add this
        input>>list[i];

This vector:

vector <int> list = {};

Has exactly zero members. You never try and increase its size so any access to this array will result in a bad result.

There are a couple of places you accesses this vector:

input>>list[i];

// and

cout<<list[k];

These are both invalid access to the list.

To fix the problem you can read the data into a value and then append it to the vector:

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

But that is not your only problem:

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

This while statement contains to calls that open a file parse the whole file and return a count. I doubt the compiler can optimize that away so that is exceedingly expensive call to make.

Can you just read values until there are none left?

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

But the proper way to do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM