gpt4 book ai didi

c++ - 我不断收到相同的错误消息 : Segment Fault (core dumped)

转载 作者:行者123 更新时间:2023-11-30 05:35:20 30 4
gpt4 key购买 nike

我对 C++ 和所有与计算机相关的东西都很陌生,所以不要着急。我第一次尝试在我类(class)的作业中使用 vector 。我设法编译了我的代码,但在运行到一半时,代码显示为 segment fault (core dumped)。我不知道如何使用 gdb 来查明确切的行,但我知道它出现在循环期间的名称函数中,以按字母顺序组织名称。我知道我的 vector 大小有问题,但我不知道如何修复它。我还需要一个简单的解决方案,因为我不是高级类,只能使用我目前在类里面学到的东西。

我也知道我为事物起的名字是多么愚蠢,事实上我在我的名字函数中塞满了太多东西......

请帮助我,尽管我的代码很困惑!

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int choice(int);
void sortAndSend(vector<string> &names);

int main()
{
ofstream outputFile;
int numOfNames;
int count = 0;
numOfNames = choice(numOfNames);

vector<string> names(numOfNames);
sortAndSend(names);

outputFile.close();
return 0;
}

int choice(int a)
{
cout << "Select a number 1-5 that reflects how many names" << endl
<< "you would like to enter." << endl;
cin >> a;
cout << "You have selected " << a << " names." << endl << endl;
return a;
}

void sortAndSend(vector<string> &names)
{
ofstream outputFile;
string name;
string a;

cout << "You will be asked to enter " << names.size() << " names." << endl
<< "You may enter each individual's "
<< "last name first, followed by the individual's first name, "
<< "then middle name (if applicable)." << endl
<< "Do NOT include any commas." << endl << endl;
cin.ignore();
for (int count = 0; count < names.size(); count++) //Allows user to enter specified # of names
{
cout << "Enter a name now: ";
getline(cin, name);
names[count] = name;
cout << endl << "You have entered " << names[count] << endl << endl;
}

for (int count = 0; count < names.size(); count++)
{
cout << names[count] << endl;
}
for (int count = 0; count < names.size(); count++)
//Arranges names in alphabetical order
//Error occurs here
{
while (names[count] > names[count + 1])
{
a = names[count + 1];
names[count + 1] = names[count];
names[count] = a;
}
}
cout << "Your names are now alphebetized" << endl << endl;
cout << "This is what is being copied to the file named"
<< " 'AlphabeticalOrderEC.txt': " << endl;

for (int count = 0; count < names.size(); count++) //Prints names in alphabetical order
{
cout << names[count] << endl;
}

outputFile.open("AlphabeticalOrderEC"); //Prints names into file
for (int count = 0; count < names.size(); count++)
{
outputFile << names[count] << endl;
}
}

最佳答案

您尝试访问不属于 vector 的地址。查看代码的这一部分:

for (int count = 0; count < names.size(); count++)
{
while (names[count] > names[count + 1])
{
a = names[count + 1];
names[count + 1] = names[count];
names[count] = a;
}
}

你应该使用count + 1,只有当count小于names.size()-1时你才必须这样做。您应该找到另一个可以替换这部分代码的逻辑。这就像试图访问只有 10 个元素的数组的第 11 个元素。

关于c++ - 我不断收到相同的错误消息 : Segment Fault (core dumped),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930008/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com