[英]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'.我正在尝试制作一个小程序来读取用户的输入,并且只接受长度为 1 的字符串。此外,它必须是“m”、“o”、“r”、“i”或'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.
当我尝试使用 char 时,它工作了一半,因为假设我在输入“mfybsn”上输入,程序刚刚检测到第一个字母(即“m”)并验证为正确。 But obviously, "mfybsn" is not = to 'm' even though my old program thinks it was for some reasons.
但很明显,“mfybsn”不是 = 'm',即使我的旧程序认为这是出于某些原因。
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.现在正如我所说,如果“userInput”的长度为 1(和其他条件),我正在尝试使用字符串只接受它,但我无法实现它。 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因为userInput是一个字符串而
CODE_METRO_BUS
和其他人是字符,并且在检查长度时错误地放置了 ')'
I encourage you to replace scanf("%s",userInput);
我鼓励你替换
scanf("%s",userInput);
by scanf("%49s",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 ...如果用户输入超过 49 个字符,则不要写出userInput ,即使读取最多 49 个字符的字符串而期望只有 1 个字符也很奇怪......
It is also interesting to check the value returned by scanf is 1检查scanf返回的值是否为 1 也很有趣
It is also strange to write Enter M
and to test m rather than M etc写
Enter M
测试m而不是M等也很奇怪
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.