在C ++中使用segfault处理数组

时间:2015-04-13 01:56:44

标签: c++ arrays string segmentation-fault

我是一个介绍性的C ++类,所以我对此完全陌生,但我似乎在运行时使用以下代码获得了一个段错误(关于我认为问题所在的位置):

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语句中的代码。 我们没有详细讨论段错误,所以我甚至不知道从哪里开始搜索这个问题。

1 个答案:

答案 0 :(得分:2)

您是硬编码的数组大小,是否有可能超过该限制?

因此,如果您的回复可以动态增长,请按以下方式声明向量

#include<vector> std::vector<std::string> responses;

按如下方式纠正你的循环:

   while (infile >> response;)
    {         
         responses.emplace_back(response);
         count ++;       

    }
     infile.close();