gpt4 book ai didi

c - 如何按字母顺序将结果存储在不同的文件中

转载 作者:太空宇宙 更新时间:2023-11-04 04:52:34 24 4
gpt4 key购买 nike

我是 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;
}
}
}

最佳答案

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() 来解决。

关于c - 如何按字母顺序将结果存储在不同的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13730764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com