gpt4 book ai didi

C:在文件中查找重复的字符串值

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

所以我有一个包含让我们说的文件:

cat
dog
cat

我正在尝试浏览文件,让它识别出有两个 cat 元素和一个 dog 元素,然后在同一个文件中编辑为:

cat - 2
dog - 1

我已经将所有单词保存在一个字符串数组 char **wordList 中,我正在尝试使用 qsort 对它们进行排序,然后将其放入上述格式。我的 qsort 函数是:

stringcmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}

void wordSort(char **wordlist)
{
size_t strings_len = numwords - 1;
qsort(wordlist, strings_len, sizeof(char*), stringcmp);
wordFile(wordlist);
}

void wordFile(char **wordlist)
{
if((outFilePtr2 = fopen(outWords, "w")) != NULL)
{
for(x = 1; x < numwords; x++)
{
fputs(wordlist[x], outFilePtr2);
fputs("\n", outFilePtr2);
}
fclose(outFilePtr2);
}
else
{
printf("File\"%s\" could not be opened.\n", outWords);
}
}

虽然它没有按顺序排序任何东西。我该如何解决?

最佳答案

以下程序适用于您对 stringcmp 的定义(这似乎是正确的):

int main (int argc, char *argv[]) {
int i;
qsort(argv, argc, sizeof(char *), &stringcmp);
for (i = 0; i != argc; i++) printf("%s\n", argv[i]);
}

因此我怀疑你对 char **wordList 的定义有问题。

更新

您的程序的这个版本略有修改/完整版本适用于我:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *outWords = "outWords.txt";
char *wordList[] = { "cat", "dog", "cat" };
#define numwords (sizeof(wordList) / sizeof(wordList[0]))
FILE *outFilePtr2;
int x;

int stringcmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}

void wordSort(char **wordlist)
{
qsort(wordlist, numwords, sizeof(char*), stringcmp);
wordFile(wordlist);
}

void wordFile(char **wordlist)
{
if((outFilePtr2 = fopen(outWords, "w")) != NULL)
{
for(x = 0; x < numwords; x++)
{
fputs(wordlist[x], outFilePtr2);
fputs("\n", outFilePtr2);
}
fclose(outFilePtr2);
}
else
{
printf("File\"%s\" could not be opened.\n", outWords);
}
}

int main() {
wordSort(wordList);
wordFile(wordList);
return 0;
}

我修改了qsort的第二个参数(否则最后一个字符串指针不会被考虑,保持不变)。我还调整了 wordFilefor 循环的初始化 x=0 以打印第一个字符串。

您可能以其他方式定义了 **wordList 导致了问题,您没有提供它的代码。

关于C:在文件中查找重复的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29834817/

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