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