c++ - 在 C++ 中使用数组获取段错误

标签 c++ arrays string segmentation-fault

我在介绍性 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/

相关文章:

c++ - 通过引用传递 vector 并在基于范围的 for 循环中更改其值?

c++ - 如何在 OS X 10.6 上针对 OS X 10.4u SDK 构建 boost 库和其他库?

java字节操作疑问

java - 替换字符(") with (\")

c++ - 如何从类型(类)转换为标准 :string?

java - Windows 上的 Thrift/Google Protocol Buffers

c++ - QSet<func pointer> 不通过 gcc 编译

c++ - 显示二维动态数组

python - 从无元素的列表中获取最大值

java - 为什么一根长字符串比许多小字符串占用更多空间?