我是編程的初學者,現在我的講座都是關於指針的主題。我應該從鍵盤輸入字符串(最多40),然後按字母順序排序。使用指針對字符串進行排序
要求輸入應該在輸入「空」字符串時立即中斷,指向字符串的指針應該存儲在數組中,排序時我應該將指針移動到字符串,我應該使用strcmp
函數。
我盯着寫我的代碼,想問你我是否在正確的軌道上。我被建議將字符串存儲在二維char
數組中,但問題是即使我輸入空行(我認爲應該只按Enter
),程序仍會詢問輸入。其次,我想問你關於排序字符串的最佳算法,因爲我沒有完全排序的經驗。
編輯我在我的代碼中做了一些改變,它給出了我期望的輸出,按字母順序對字符串進行排序。但是,如果我的代碼中有任何重大缺陷,並且可能會做出一些改進,我會非常感謝C中更有經驗的人的意見。在部分我不明白一個指針被分配了一個地址,但是我創建指針數組的方式真的是最有效的嗎?我知道我可以使用malloc
,但我想像我一樣使用2D陣列。
int count = 0;
char arr[40][100];
char (*poi[40])[100]; //Is the array of pointers declared right?
for (int i = 0; i < 40; i++)
{
fgets(arr[i], 101, stdin);
count++;
if (strcmp(arr[i], "\n") == 0)
{
break;
}
}
printf("\n");
for(int i = 0; i < count; i++)
{
poi[i] = &arr[i]; //I don't really understand how this part works, seems to work though
}
for(int i = 0; i < count - 1; i++)
{
for(int j = i + 1; j < count; j++)
{
if(strcmp(*poi[i], *poi[j]) > 0) //if I type here strcmp(arr[i], arr[j]) the output is not sorted properly, why?
{
char (*temp)[100] = poi[i];
poi[i] = poi[j];
poi[j] = temp;
}
}
}
//returns sorted strings
for (int i = 0; i < count; i++)
{
printf("%s", *poi[i]);
}
第一步是確定您需要使用哪種編程語言編寫代碼。 – juanchopanza
@juanchopanza沒有要求我的入門課程有「C」和「C++」兩個元素。我會很感激一個建議。 – Theta
C++,'std :: string','std :: sort'。 – juanchopanza