【发布时间】:2020-05-05 18:45:06
【问题描述】:
我正在尝试将包含 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];
}
}
【问题讨论】:
-
我强烈建议在发帖前先搜索一下互联网。 StackOverflow 上已经有很多同名的问题。还可以在互联网上搜索“C++ 读取文件逗号分隔”以获取从文本文件读取的示例。
-
您可能希望在阅读每一行时保留
std::vector的文件位置。这将允许您更有效地访问文件中的一行(查找文件位置,然后将文件位置设置为该值)。 -
您的代码存在c - Why is “while ( !feof (file) )” always wrong? - Stack Overflow 中描述的问题。您通过从
count中减去 1 来解决此问题,但是您的程序会将 0 行文件报告为具有 -1 行。