【发布时间】:2020-03-26 12:35:31
【问题描述】:
我正在尝试在我研究的书中做这个编程项目:
编写一个程序,对用户输入的一系列单词进行排序:
输入单词:foo
输入单词:bar
输入单词:baz
输入单词:qux
输入单词:
按排序顺序:bar baz foo quux
假设每个单词的长度不超过 20 个字符。当用户输入一个空词时停止阅读(即,按 Enter 而不输入一个词)。将每个单词存储在动态分配的字符串中,使用指针数组来跟踪字符串。
读取所有单词后,对数组进行排序(使用任何排序技术),然后使用循环按排序顺序打印单词。
这就是我正在尝试的:
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 20
int compare ( const void * p, const void * q);
int main (void){
int n;
printf("How many words do you want to write");
scanf("%d", &n);
fflush(stdin);
char * word[n];
for( int i = 0; i < n; i++){
fprintf(stdout , "Waiting for the word:");
if(fgets(word[i] , MAX_LENGTH +1 , stdin) == "\n")
break;
}
qsort((void *)word,n,sizeof(int),compare);
printf("Ordered list is:\n\n");
for( int i = 0; i < n; i++){
fprintf(stdout , "\t %s", word[i]);
}
}
int compare (const void * p, const void * q){
return strcmp( * (char**) p , * (char **) q);
}
编辑:感谢这里的编码人员,斜体问题得到了解决。我的新问题是我无法读取数组的第一个元素。程序自行关闭。
C:\Users\Lenovo\Desktop\ogrenme\ch17>sorting
How many words do you want to write4
Waiting for the word:asd
C:\Users\Lenovo\Desktop\ogrenme\ch17>
还有一个烦人的错误让我无法完成练习,并让我对这本具有挑战性的书的其余部分“冷静”:
sorting.c:20:5: warning: implicit declaration of function 'qsort' [-Wimplicit-function-declaration]
qsort((void *)word,n,sizeof(int),compare);
【问题讨论】:
-
请
#include <stdlib.h>获取qsort()的函数声明。 -
投票结束是一个简单的错字。包含函数所在的header,就这么简单。
-
man qsort将向您显示所需的#includes。如果你不使用 UNIX/Linux 系统,你可以在你最喜欢的搜索引擎中输入这个。 -
另外请注意
if(fgets(word[i] , MAX_LENGTH +1 , stdin) == "\n")中的错误。fgets()的返回值将永远与字符串文字相同。请看Removing trailing newline character from fgets() input -
@Lundin 并不是那么简单。更多:没有为指针数组
char * word[n];的元素分配内存。遗憾的是,代码有多个错误,而不仅仅是一个简单的错字。