Home > Back-end >  scanf() adds character to string
scanf() adds character to string

Time:03-09

I have this code and it keeps adding what ever the guesses string is to the wordle string when I compare them, resulting in them to never be the same. How can I fix this?

#include <string.h> 

int main() {
    char wordle[5];
    char guesses[5];
    int guess = 5;
    int value;
   
    printf("Please input a secret 5 letter word:\n");
    scanf("%s",wordle);
    

    
    while (guess != 0){
        printf("You have %d tries, please guess the word\n",guess);
        scanf("%s",guesses);
        
        value = strcmp(wordle,guesses);
        
        if (value == 0){
            printf("you win\n");
            break;
        }
        guess = guess - 1;
    }
  
    return 0;
}```

CodePudding user response:

Your strings for wordle and guesses are too short. You need to make room for '\0'. They should be 6 bytes long not 5.

char wordle[6];
char guesses[6];

CodePudding user response:

Your program has undefined behavior. You're making two mistakes.

  1. If your user enters 5 characters, it takes 6 characters to store the string. The program would attempt to write a null terminator into wordle[5] which is not a valid index.

  2. Your user could enter any number of letters. You need to make sure they don't overflow your buffer.

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

int main() {
    char wordle[6];
    char guesses[6];
    int guess = 5;
    int value;

    int chars_read;
    do {
        printf("Please input a secret 5 letter word:\n");
        chars_read = scanf("%5s%*s\n", wordle);
    } while(chars_read != 1 && strlen(wordle) != 5);
    
    while (guess != 0){
        do {
            printf("You have %d tries, please guess the word\n", guess);
            chars_read = scanf("%5s%*s\n", guesses);
        } while(chars_read != 1 && strlen(wordle) != 5);
        
        value = strcmp(wordle, guesses);
        
        if (value == 0){
            printf("you win\n");
            break;
        }
        guess = guess - 1;
    }
  
    return 0;
}

See it in action

scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s

MSC24-C. Do not use deprecated or obsolescent functions

  • Related