我试图将 in.txt 文件中的单词放入一个数组中,并按字母顺序显示该单词。我知道我的代码中有错误。请帮助我! 首先,我逐行显示文件中的单词并且有效。 但我有一个错误
cannot convert char to char * I've tried to chance
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char c,s[20];
char *p,*d[20];
int i,x;
FILE *f;
f=fopen("in.txt","r");
if (f==NULL)
{
printf("Erroe reading file\n");
exit(1);
}
while(!feof(f))
{
fgets(s,100,f);
p=strtok(s," \n");
while (p!=NULL)
{
printf("%s \n",p);
p=strtok(NULL," \n");
}
}
while(!feof(f))
{
fgets(s,100,f);
p=strtok(s," \n");
while(p)
{
for(i=0;i<100;i++)
strcpy(d[i],p);
if(x=strcmp(d[i],d[i+1])<0)
{
c=d[i];
d[i]=d[i+1];
d[i+1]=c;
}
else
p=strtok(NULL," \n");
}
}
for(i=0;i<100;i++)
printf("%s",d[i]);
}
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_LENGTH 31
#define MAX_WORDS 128
#define S_(n) #n
#define S(n) S_(n)
int cmp(const void *a, const void *b){
return strcmp(*(char**)a, *(char**)b);
}
int main(void){
char s[MAX_WORD_LENGTH+1];
char *d[MAX_WORDS];
int i, n = 0;
FILE *f;
f=fopen("in.txt", "r");//Error handling is omitted
while(1==fscanf(f, "%" S(MAX_WORD_LENGTH) "s", s)){
if(n < MAX_WORDS)
d[n++] = strdup(s);//make s's clone
else
break;
}
fclose(f);
qsort(d, n, sizeof(*d), cmp);
for(i=0;i<n;i++){
printf("%s\n", d[i]);
//free(d[i]);
}
return 0;
}
<小时/>
fgets-strtok 版本。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 128
int cmp(const void *a, const void *b){
return strcmp(*(char**)a, *(char**)b);
}
int main(void){
char s[128];
char *d[MAX_WORDS];
int i, n = 0;
FILE *f;
f=fopen("in.txt", "r");//Error handling is omitted
while(fgets(s, sizeof(s), f)){
char *p = strtok(s, " \t\n");
while(p){
if(n < MAX_WORDS)
d[n++] = strdup(p);//make s's clone
else
goto out;
p = strtok(NULL, " \t\n");
}
}
out:
fclose(f);
qsort(d, n, sizeof(char*), cmp);
for(i=0;i<n;i++){
printf("%s\n", d[i]);
//free(d[i]);
}
return 0;
}
关于c - 将 .txt 中的单词转换为 C 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26004767/