我想編寫一個程序,在命令行中的用戶將會把他們想進入名的數量,然後他們鍵入帶有名字和姓氏的名字,像下面:我該如何解決這個排序錯誤?
./Sort-names 5
Andrew Hawking
John Smith
Stephen Hawking
Alice Cooper
Jean Smith
,然後我會獲得這些投入,並與字母排序姓氏排序,所以theout放應該是:
Alice Cooper
Andrew Hawking
Stephen Hawking
Jean Smith
John Smith
這裏是我的代碼:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <cstdlib>
#include <cstring>
#include <ctype.h>
using namespace std;
//Identify space in a line
int locateLastName (char name[][20], int i, int j) {
int locate = 0;
while (name[i][j] && locate == 0) {
if (isspace(name[i][j])) {
locate = 1;
}
j++;
}
return j;
}
int main(int argc, const char * argv[]) {
int x = atoi(argv[1]); //the number of names
char name[x][20]; //names in 2d array
char nameCopy[20]; //for bubble sort
//get the input names
for (int i = 0; i < x; i++) {
cin.getline(name[i],20);
}
//bubble sort the last name
for (int i = 0; i < x-1; i++) {
for (int j = 0; j < x-1; j++) {
int a = locateLastName(name, j, 0);
int b = locateLastName(name, j+1, 0);
int haveChange = 0;
while (name[j][a] && name[j+1][b] && haveChange == 0) {
if (name[j][a] > name[j+1][b]) {
strcpy(nameCopy, name[j]);
strcpy(name[j], name[j+1]);
strcpy(name[j+1], nameCopy);
haveChange = 1;
}
a++;
b++;
}
}
}
int line = 0;
while (line < x) {
cout << name[line] << endl;
line++;
}
return 0;
}
然而,在執行我的程序後產生以下結果:
./Sort-names 5
Andrew Hawking ->input
John Smith
Stephen Hawking
Alice Cooper
Jean Smith
John Smith ->output
Andrew Hawking
Jean Smith
Stephen Hawking
Alice Cooper
誰能幫我找到了這個錯誤,我不知道什麼是錯的。
最好的方法是先使用調試程序遍歷代碼,然後檢查代碼在哪裏出現意外路徑。 –
使用'string','vector'和'sort' – BLUEPIXY
除了@ BLUEPIXY的建議,不要使用'atoi',而要使用'std :: stoi',不要使用專有的GCC變長數組,使用'cin.getline'但是'std :: getline',不要使用多維數組......基本上,不要使用所有這些錯誤的部分,因爲它們使得難以解決程序的真正問題邏輯。 –