【问题标题】:How to store a result in different files alphabetically如何按字母顺序将结果存储在不同的文件中
【发布时间】:2012-11-23 17:21:44
【问题描述】:

我是 C 的新手。 我有一串单词,例如一篇新闻报纸文章 我想将文章中的单词按字母顺序存储在不同的文件中 比如“我所看到的都是灵感,但我不想被淹没”。

现在,在上面的示例中,我想将所有以'a' 开头的单词存储在文件a.txt 中。同样以'b'开头的单词要存储在b.txt

我正在使用下面的语法,但这不起作用

{
    if(strcmp(wordcheck, worddict)==0)
        fprintf(out_file1 ,"%c", wordcheck); //storing the value in a.txt            
}

我还有一个问题,如果我获取一个包含单词列表的文本文件,并且我希望将此列表与许多列表(已经提供给程序)进行比较,这意味着输入列表中的任何单词是否匹配与任何来源列表中的单词我希望仅当在 list1.txt 中找到该单词时将该单词存储在文件 a.txt 中)。同样,如果在 list2.txt 中找到该单词,我希望将其存储在 b.txt 中。除此之外,我想在输出文件 a.txt 中显示文件 list1.txt 的路径。 喜欢 唱./dataset/dictionary/verb

我使用了下面的语法

while(dictcount >= 0)//reads dictionary word into array//
{   
    dictcount = 0; //searches through all of the listed data files
    fscanf(fp1,"%s", worddict);
    fscanf(fp2,"%s", worddict);
    fscanf(fp3,"%s", worddict);
    if(strcmp(wordcheck, worddict)==0)//compare strings//if the word in found in list misc.txt
    {
        fprintf(out_file1 ,"%c", wordcheck); //storing the value in output_misc.txt
        if (getcwd(cwd, sizeof(cwd)) != NULL) {
            //fprintf(out_file3, "%c\n", cwd); //stores the path of the folder containing the list in which the matched 'word' is found  
            return 0;
        }
    }
}

【问题讨论】:

    标签: c file store


    【解决方案1】:

    strcmp() 将比较整个字符串,而不仅仅是您感兴趣的部分。所以'abcdef' 将不等于'a',但如果您使用strncmp() 并告诉它只比较 1 个字节会做你想做的事。

    但是,你只比较了 1 个字节,为什么不这样做:

    ...
    store_words(out_file, words, n_words, 'a');
    ...
    void store_words(FILE *out_file, char *words, int n_words. char starter) {
        int i;
        for(i=0; i < n_words; i++) {
            if(words[i][0] == starter) { // check if the first character is 'a' */
                fprintf(out_file ,words[i]); //if so storing the value in a.txt            
            }
        }
    }
    

    然后循环遍历字母表中的所有字符? 请注意,C 认为 'a' 和 'A' 是不同的,但这可以通过 tolower() 来解决。

    【讨论】:

    • 如果我使用包含要排序的文本的文本文件会怎样
    • 那你需要先加载,打开文件写入会覆盖内容。
    • 我还有一个问题。我在第一个问题中添加了它。你能看看吗?
    • 那么,现在你将用你的三个读取覆盖 worddict,我不明白 getcwd() 应该完成什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多