为什么fgets()和strncmp()在此C代码中无法进行字符串比较? [英] Why is fgets() and strncmp() not working in this C code for string comparison?

查看:137
本文介绍了为什么fgets()和strncmp()在此C代码中无法进行字符串比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我遇到的一个非常有趣的问题.我做了很多关于堆栈溢出的搜索,发现其他人也有类似的问题.因此,我相应地编写了代码.我本来有fscan()strcmp(),但是那完全炸了我.因此,其他帖子建议使用fgets()strncmp()并使用长度进行比较.

This is a very fun problem I am running into. I did a lot of searching on stack overflow and found others had some similar problems. So I wrote my code accordingly. I originally had fscan() and strcmp(), but that completely bombed on me. So other posts suggested fgets() and strncmp() and using the length to compare them.

我试图通过打印出两个字符串的大小来调试我正在做的事情.我以为,也许他们有/n漂浮在里面或什么东西弄乱了它(另一篇文章谈到了这一点,但是我不认为这是发生在这里).因此,如果大小相同,则strncmp()的限制应相同.正确的?只是为了确保它们被正确地比较.现在,我知道如果字符串相同,它将返回0,否则返回strncmp()的负数.但这不起作用.

I tried to debug what I was doing by printing out the size of my two strings. I thought, maybe they have /n floating in there or something and messing it up (another post talked about that, but I don't think that is happening here). So if the size is the same, the limit for strncmp() should be the same. Right? Just to make sure they are supposedly being compared right. Now, I know that if the strings are the same, it returns 0 otherwise a negative with strncmp(). But it's not working.

这是我得到的输出:

perk
repk
Enter your guess: perk
Word size: 8 and Guess size: 8
Your guess is wrong
Enter your guess: 

这是我的代码:

void guess(char *word, char *jumbleWord)
{
        size_t wordLen = strlen(word);
        size_t guessLen; 
        printf("word is: %s\n",word);
        printf("jumble is: %s\n", jumbleWord);


        char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1));
        do
        {
            printf("Enter your guess: ");
            fgets(guess, MAX_WORD_LENGTH, stdin);
            printf("\nword: -%s- and guess: -%s-", word, guess); 
            guessLen = strlen(guess);
            //int size1 = strlen(word);
            //int size2 = strlen(guess); 

            //printf("Word size: %d and Guess size: %d\n",size1,size2);


            if(strncmp(guess,word,wordLen) == 0)
            {
                printf("Your guess is correct\n"); 
                break; 
            }

            }while(1);
    }

我从以下建议中进行了更新.特别是在学习了char *作为指针和将某些内容称为 string 之间的区别之后.但是,它仍然给我同样的错误.

I updated it from suggestions below. Especially after learning the difference between char * as a pointer and referring to something as a string. However, it's still giving me the same error.

请注意,MAX_WORD_LENGTH是在程序顶部用作

Please note that MAX_WORD_LENGTH is a define statement used at the top of my program as

#define MAX_WORD_LENGTH 25

推荐答案

sizeof(guess)返回的是char *的大小,不是字符串的长度.您的问题是您正在使用sizeof来管理字符串长度. C具有字符串长度的功能: strlen .

sizeof(guess) is returning the size of a char * not the length of the string guess. Your problem is that you're using sizeof to manage string lengths. C has a function for string length: strlen.

sizeof用于确定数据类型和数组的大小. sizeof仅在一种非常特殊的情况下适用于字符串-我在这里不做介绍-但即使如此,也始终使用strlen处理字符串长度.

sizeof is used to determine the size of data types and arrays. sizeof only works for strings in one very specific case - I won't go into that here - but even then, always use strlen to work with string lengths.

您将要确定允许单词使用的字符数.这是游戏的属性,即游戏中的单词永远不会超过11个字符.

You'll want to decide how many characters you'll allow for your words. This is a property of your game, i.e. words in the game are never more that 11 characters long.

所以:

// define this somewhere, a header, or near top of your file
#define MAX_WORD_LENGTH 11

// ...

size_t wordlen = strlen(word);
size_t guessLen;

// MAX_WORD_LENGTH + 1, 1 more for the null-terminator:
char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1));

printf("Enter your guess: ");
fgets(guess, MAX_WORD_LENGTH, stdin);

guessLen = strlen(guess);

还要查看fgets的文档,并注意换行符 保留在输入中,因此,如果要比较两个单词,则需要考虑这一点.一种快速解决方案是仅比较word的长度,而不比较 的长度,因此:if( strncmp(guess, word, wordLen) == 0).此快速修复的问题在于它将传递无效的输入,即如果wordeject,而guessejection,则比较将通过.

Also review the docs for fgets and note that the newline character is retained in the input, so you'll need to account for that if you want to compare the two words. One quick fix for this is to only compare up to the length of word, and not the length of guess, so: if( strncmp(guess, word, wordLen) == 0). The problem with this quick fix is that it will pass invalid inputs, i.e. if word is eject, and guess is ejection, the comparison will pass.

最后,没有理由在循环的每次迭代中为新的guess分配内存,只需使用已经分配的字符串即可.您可以将功能设置更改为:

Finally, there's no reason to allocate memory for a new guess in each iteration of the loop, just use the string that you've already allocated. You could change your function setup to:

char guess(char *word, char *jumbledWord)
{
    int exit;

    size_t wordLen = strlen(word);
    size_t guessLen; 

    char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1));

    do
    {
        printf("Enter your guess: ");
        // ...

这篇关于为什么fgets()和strncmp()在此C代码中无法进行字符串比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆