Home > Net >  Comparing user input from strings
Comparing user input from strings

Time:01-30

I am trying to make a simple game similar to the now popular game Wordle, but I am having trouble comparing a user inputted string to that of a pre-existing string. I want to be able to compare the strings as a whole as well as each individual letter in the input and the answer. Here is the code i am working with:

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

int main()
{
    char guess[5];
    char answer[5] = "money";
    printf("what is your first guess? ");
    scanf("%s",&guess);
    
    if (strcmp(guess,answer) == 0){
        printf("\nyour guess was correct");
    }
    else{
        printf("Your guess was incorrect");
    }

    return 0;
}

CodePudding user response:

The user may input significantly more characters than 5-1=4.
Also, use fgets(), not scanf().

char guess[100];

fgets( guess, sizeof(guess), stdin );

Don’t forget to remove the Enter key from the user’s input:

char * p = strchr( guess, '\n' );
if (p) *p = '\0';

When storing constant character arrays, declare it with a pointer:

const char * answer = "money";

If you have a fixed list of answers, use the const array.

When storing mutable character arrays, declare it either with a large space (for future use):

char answer[100] = "money";

or let the compiler declare the exact number of elements you need:

char answer[] = "money";

I presume you will want to randomly select an answer for the user to guess at some point, so the 100-element array is a better choice. Use this if you wish to have a file of answers to use at some point.

You will probably want to normalize the user’s input in some way as well. For example, if all your answers are lowercase, you should transform user input to lowercase before comparing.

#include <ctype.h>

char * stolower( char * s )
{
  for (char * p = s;  *p;    p)
    *p = tolower( *p );
  return s;
}

if (strcmp(tolower(guess),answer) == 0){

CodePudding user response:

C strings like "money" contains 6 chars, with an extra '\0' to mark the end of a string. Which means, when stored with a char array, you'll always need an extra space for '\0' in order to use the char array as a string.

For example, strcmp for char str[10] = "aaa\0bbb" and char[4] = "aaa" will be 0 (equal), because the program will see '\0' as the end of a string, ignoring the extra chars. (btw, the way "aaa" stored in the char array is like this: ['a', 'a', 'a', '\0'])

  •  Tags:  
  • Related