C 用户输入验证 - 只需要一个转换为 int 的字符
我在 C 中获取用户输入时遇到问题。我只想获取第一个数字。我从字符中过滤用户输入,但是当我输入 2 位数字(错误的用户输入)时,程序开始表现得很奇怪,
它显示:
Turn 2 : What number? 21
Turn 2 : What number? 1 6 2 4 2
//User input validation
int GetColorGuess(int counter)
{
int color=1;
int inputChar=' ';
do{
printf("Turn %d : What number? ",counter);
inputChar=getchar();
getchar();
}
while(inputChar<((int)'1') || inputChar>selectedColorSize+'0');
color = digit_to_int(inputChar);
return color;
}
//convert char which represents digit to int
int digit_to_int(char d)
{
char str[2];
str[0] = d;
str[1] = '\0';
return (int) strtol(str, NULL, 10);
}
任何人都可以帮我解决问题吗?
I have problem taking user input in C. I want to take the first number only. I filter the user input from characters but when I enter 2 digits(wrong user input) the program starts to behave strange
it displays:
Turn 2 : What number? 21
Turn 2 : What number? 1 6 2 4 2
//User input validation
int GetColorGuess(int counter)
{
int color=1;
int inputChar=' ';
do{
printf("Turn %d : What number? ",counter);
inputChar=getchar();
getchar();
}
while(inputChar<((int)'1') || inputChar>selectedColorSize+'0');
color = digit_to_int(inputChar);
return color;
}
//convert char which represents digit to int
int digit_to_int(char d)
{
char str[2];
str[0] = d;
str[1] = '\0';
return (int) strtol(str, NULL, 10);
}
Can anyone help me what is the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当输入“21”时,您的第一个
getchar()
读取“2”,下一个getchar()
(可能应该吃掉换行符)读取“1”。然后输入“3”时,第一个getchar()
读取换行符,第二个getchar()
读取“3”。更改您的代码以使用sscanf
代替。When entering "21" your first
getchar()
reads the '2', the nextgetchar()
, which probably should eat the newline, reads the '1'. when then entering "3" your firstgetchar()
reads the newline and your secondgetchar()
reads the '3'. Change your code to usesscanf
instead.