我有一个文本文件,其中仅包含带有如下消息的行:
Hello there
howdy
现在我得到了这个读取这些行并返回包含它们的数组的函数。
string* printlines(string filename)
{
string line;
int sum = 2;
int i =0;
string *quotes;
ifstream infile(filename.c_str());
quotes= new string[2];
if (infile.is_open())
{
while (infile.good())
{
getline (infile,line);
quotes[i] = line; // <--- here's the problem
i++;
}
}
infile.close();
return quotes;
}
gdb 报告粗体行有问题,但我没有看到。
最佳答案
循环结构不正确,将导致超出数组末尾。即使文件中只有两行,在 getline()
之后也没有检查以确定是否成功。将读取前两行,但 eof 尚未设置,导致第三行 getline()
调用,超出数组的末尾。
更改为:
while (getline(infile, line) && i < 2)
{
quotes[i] = line;
i++;
}
话虽如此,考虑使用 std::vector<std::string>
而不是数组:
std::vector<std::string> quotes;
while (getline(infile, line))
{
quotes.push_back(line);
}
std::vector
将动态增长以存储所有读取行。无需更改代码即可将新行添加到文本文件。
关于c++ - 字符串分配的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10554404/