c - 将 .txt 中的单词转换为 C 中的数组

标签 c arrays file

我试图将 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/

相关文章:

file - HTTP 路径必须以斜杠开头吗?

java - 未插入新行

c - 将从文件中读取的不同字符串插入到链接列表中

c - 查找最小值和最大值

php - 如何解决 cURL Post 不发布数据的问题?

java - 是否可以在不创建新数组的情况下从 Java 数组中替换/删除元素?

file - Yii2中的函数下载

c - 在接触大内存区域时执行 fork exec 的程序

c - 为什么输入 "abc!!!"但输出不是 "abc+++"?

javascript - 使用 Jquery 用索引或位置而不是键名解析 JSON 对象?