1
我對C++和所有計算機相關的東西都很陌生,所以很容易。我正在嘗試在我班的作業中首次使用矢量。我設法讓我的代碼編譯,但運行一半,代碼讀取segment fault (core dumped)
。我不知道如何使用gdb查明確切的行,但我知道它發生在循環過程中的名稱函數中以按字母順序組織名稱。我知道我的矢量大小有問題,但我不知道如何解決它。我還需要一個簡單的解決方案,因爲我不是高級班,只能使用我在課堂上學到的知識。我不斷收到相同的錯誤消息:段錯誤(核心轉儲)
我也是意識到了自己的東西的名字多麼愚蠢的,而事實上,我已經擠了這麼多了我的名字......功能
請幫助我,儘管我的代碼的混亂自然!
#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;
}
}
我編輯過將'gbd'改爲'gdb',但想要確保你實際上使用了正確的命令! 'gdb',然後在gdb中輸入'run'。當它出現段錯誤時,輸入'bt'獲得回溯。 –
dga
如果'count' =='names.size() - 1',那麼'count + 1' == names.size()'和'names [count + 1]'在數組邊界之外。 –
感謝您的幫助和錯字修復!這是一個簡單的修復!我錯過了這一點,我感到很傻。 – TingRay