c - 在 C 中使用 strcmp() 函数

标签 c strcmp ansi-c

我正在编写一个程序,应该从命令中输入,然后找到输入的词频。我在使用 strcmp() 函数比较字符串(字符数组)时遇到问题。我已经研究了几个小时,但我仍然不明白我做错了什么。和指针有关系吗?这是我的代码:

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

int main(){
    char Words[501][21];
    int FreqNumbers[500];
    char temp[21] = "zzzzz";
    char Frequency[5][21];
    int wordCount = 0;
    int numberCount = 0;
    int i = 0;
    int counter = 0;
    int end = 0;

    do {
        scanf("%20s",Words[wordCount]);
        for(counter = 0;counter < wordCount;counter++){
            if(wordCount > 0){
                if(strcmp(Words[wordCount], Words[counter]) == 0){
                    FreqNumbers[counter]++;
                    break;
                }
                FreqNumbers[wordCount]++;
            }
        }
        wordCount++;
        printf("%s", Words[wordCount - 1]);
        printf("%s", temp);
    } while(strcmp(Words[wordCount],&temp) != 0);

    return(0);
}

最佳答案

strcmp函数中,它不是将用户输入的单词与“zzzzz”进行比较,而是用“zzzzz”检查数组中的下一个条目,因此它不会终止,因为从来没有匹配项。 (正如您在 wordCount++; 函数之前所做的 strcmp 一样)

char temp[10] - 10 个字符的数组,其中 temp将会指向。 (不可变/不变)。

您正在传递strcmp函数,指向内存的变量的地址,而应该给它一个指向内存的指针。(有点令人困惑,但我希望你明白)。所以理想情况下应该给予它。

strcmp(Words[wordCount],temp);strcmp(Words[wordCount],&temp[0]);

尽管我所说的可能有点令人困惑。我强烈推荐您查看KnR并特别读取数组 array of chars

我对您的代码做了一些更改。现在它正在按要求工作。请看一下,如果可以接受的话标记为答案

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

int main(){

    char Words[501][21]={{0}};          //zero initialized
    char *temp = "zzzzz";       //string literal
    int FreqNumbers[500],wordCount = 0,counter = 0;     //other variables

    do {

        scanf("%s",Words[wordCount]);

        for(counter = 0;counter < wordCount;counter++){

            if(wordCount > 0){
                if(strcmp(Words[wordCount], Words[counter]) == 0){
                    FreqNumbers[counter]++;
                    break;
                }
                FreqNumbers[wordCount]++;
            }
        }
        wordCount++;
        printf("%s\n", Words[wordCount - 1]);           //print if required
        printf("%s\n", temp);                           //print if required

    } while(strcmp(Words[wordCount-1],temp) != 0);      

    return(0);
}

关于c - 在 C 中使用 strcmp() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10711826/

相关文章:

c++ - char 数组访问冲突

c - 为什么 Xcode 允许我在任何地方声明 C 变量?

c - (*++argv)[0] 和 while(c = *++argv[0]) 的区别

c - 如何将汇编代码关联到 C 程序中的确切行?

c - aligned_alloc 函数要求

c++ - 字符串的值不同,但打印它们显示相同的值

c - strncmp() 表达式中的 strlen() 是否会破坏在 strcmp() 上使用 strncmp() 的目的?

c - 从 ANSI C 中的字符串中获取特定行

每行扫描数字的可变数量(scanf)

c - 按 "b=(a+b)-(a=b);"进行交换是否安全?