我在介绍性 C++ 类(class)中,所以我对此完全陌生,但我似乎在运行时使用以下代码遇到段错误(精简到我认为问题所在的位置):
int main(int argc, char *argv[])
{
string filename;
ifstream infile;
float average;
int const ARRAY_SIZE = 20;
int count = 0;
string responses[ARRAY_SIZE];
string response;
char grade;
welcome();
splash();
cout << showpoint << setprecision(1) << fixed;
cout << "\n\n\n\n\n\n\n\n\n\n\n"
<< "\t\tEnter 8-Ball response file name: ";
cin >> filename;
infile.open(filename.c_str());
system("CLS");
cout << "score";
cout << "\n\n\n\n";
if (infile)
{
while (!infile.eof())
{
infile >> response;
if (1==1)
{
responses[count] = response;
count ++;
}
}
infile.close();
}
cout << "\n\n\n";
system("PAUSE");
return 0;
}
那里有一些额外的行、变量等,只是因为这是从各种旧程序中拼凑而成的,我没有包括这些函数,因为这似乎不是问题所在。基本上,每当我输入文件名时,都会出现段错误。它打印“分数”,所以它在那之后,我尝试取出 if 部分,但它仍然让我感到悲伤,所以问题似乎出在 while 语句中的代码上。 我们还没有详细讨论段错误,所以我什至不知道从哪里开始搜索问题。
最佳答案
您对数组大小进行了硬编码,它是否有可能超过该限制?
所以如果你的响应可以动态增长,声明一个 vector 如下
#include<vector>
std::vector<std::string> responses;
并按如下方式更正循环:
while (infile >> response;)
{
responses.emplace_back(response);
count ++;
}
infile.close();
关于c++ - 在 C++ 中使用数组获取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29596843/