简体   繁体   中英

Validating a user input "string" length (C language)

I'm trying to make a small program that reads the input from a user, and only accept a String with a length of 1. Also, it must either be a 'm', 'o', 'r', 'i' or 'c'.

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

#define CODE_METRO_BUS 'm'
#define CODE_OMNIBUS 'o'
#define CODE_RAPIDE 'r'
#define CODE_INTEGRE 'i'
#define CODE_CARTE_ORANGE 'c'

char userInput[50];

printf("Enter the desired service:\n");
printf("\n");
printf("(Enter M) Metro/Bus\n");
printf("(Enter O) Train/Omnibus\n");
printf("(Enter R) Train rapide\n");
printf("(Enter I) Transport integre\n");
printf("(Enter C) Carte orange\n");
printf("\n");
printf("Choice: ");

fflush(stdin);
scanf("%s",userInput);
while ((userInput!= CODE_METRO_BUS &&
        userInput!= CODE_OMNIBUS &&
        userInput!= CODE_RAPIDE &&
        userInput!= CODE_INTEGRE &&
        userInput!= CODE_CARTE_ORANGE) ||
        (strlen(userInput> 1)) ) {

    printf("Error! Retry: ");
    fflush(stdin);
    scanf("%s",userInput);
}

I'm just really not sure how I could do it. When I tried by using char, it was half working because, let's say I entered on input "mfybsn", the program just detected the first letter (which is 'm') and it validated as correct. But obviously, "mfybsn" is not = to 'm' even though my old program thinks it was for some reasons.

Now as I said, I'm trying to use strings to only accept "userInput" if it has a length of 1 (and other conditions), but I can't manage to achieve it. Thanks in advance.

you want :

while ((*userInput!= CODE_METRO_BUS &&
        *userInput!= CODE_OMNIBUS &&
        *userInput!= CODE_RAPIDE &&
        *userInput!= CODE_INTEGRE &&
        *userInput!= CODE_CARTE_ORANGE) ||
        (strlen(userInput) > 1)) ) {

because userInput is a string while CODE_METRO_BUS and others are characters, and a ')' is wrongly placed when you check the length


I encourage you to replace scanf("%s",userInput); by scanf("%49s",userInput); to not write out of userInput if the user enter more than 49 characters, even it is strange to read a string up to 49 characters while expecting just 1 char ...

It is also interesting to check the value returned by scanf is 1


It is also strange to write Enter M and to test m rather than M etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM