我正在尝试将包含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];
}
}
使用之前必须分配元素。
解决方法之一:
while (i <= count_line() && count_line() > 0){
if (list.size() <= (size_t)i) list.resize(i + 1); // add this
input>>list[i];