【发布时间】:2014-12-08 20:58:28
【问题描述】:
我在尝试读取文本文件的行并将它们放入程序中的相应字符串时遇到此段错误。
if(infile.is_open()){
//calculating the number of lines
while(getline(infile, line)){
numberoflines++;
}
//Find start of the file and start reading
infile.clear();
infile.seekg(0, ios::beg);
if(!infile.eof()){
//Allocate an array of strings, each string contains a line from the input file
string STRING[numberoflines];
int i = 0;
while(getline(infile, STRING[i])){
cout<<STRING[i]<<endl;
i++;
}
}
infile.close();
}
程序实际上打印出每一行,但在提供更大的文本文件时以段错误终止。
【问题讨论】:
-
什么是
STRING?为什么要调用变量STRING? -
什么是更大?你的程序中的行数是否大于
numberoflines? -
我闻到了stackoverflow的味道,使用
std::vector<std::string> lines(numberoflines); -
numberoflines 是否初始化为 0 ?在哪里?
-
C++ 没有动态大小的内置数组。如果您的代码编译,它使用扩展。你最好使用
std::vector<std::string>并使用push_back(line)添加字符串。
标签: c++ string file text segmentation-fault