如何从输入字母或数字prevent用户? [英] How to prevent users from inputting letters or numbers?

查看:105
本文介绍了如何从输入字母或数字prevent用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题;

I have a simple problem;

下面是code:

#include<stdio.h>
main(){
 int input;
 printf("Choose a numeric value");
 scanf("%d",&input);
}

我希望用户只输入数字...
所以它是这样的:

I want the user to only enter numbers ... So it has to be something like this :

#include<stdio.h>
main(){
 int input;
 printf("Choose a numeric value");
 do{
   scanf("%d",&input);
 }while(input!= 'something');
}

我的问题是,我不知道该怎么在'东西'替换...如何从输入字母字符prevent用户?

My problem is that I dont know what to replace in 'something' ... How can I prevent users from inputting alphabetic characters ?

修改

我刚刚得到一些有趣的事情:

I just got something interesting :

#include<stdio.h>
main(){
 int input;
 printf("Choose a numeric value");
 do{
   scanf("%d",&input);
 }while(input!= 'int');
}

添加'诠释'将不断循环,只要我输入数字,我想'字符',但没有工作..肯定有一些是字母吧? :•
请回复!

Adding 'int' will keep looping as long as I enter numbers, I tried 'char' but that didnt work .. surely there is something for alphabets right ? :S Please reply !

感谢您的帮助!

推荐答案

与strtol 库函数将一个字符串重新一批presentation转换为其对应的整数值,并还将设置一个指针不匹配有效数字的第一个字符。

The strtol library function will convert a string representation of a number to its equivalent integer value, and will also set a pointer to the first character that does not match a valid number.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
...
int value;
char buffer[SOME_SIZE];
char *chk;
do 
{
  printf("Enter a number: ");
  fflush(stdout);
  if (fgets(buffer, sizeof buffer, stdin) != NULL)
  {
    value = (int) strtol(buffer, &chk, 10); /* assume decimal format */
  }
} while (!isspace(*chk) && *chk != 0);

如果 CHK 点,比空白或者一个字符串结束其他的东西(0),则该字符串不是有效的整型常量。对于浮点输入,使用的strtod

If chk points to something other than whitespace or a string terminator (0), then the string was not a valid integer constant. For floating-point input, use strtod.

这篇关于如何从输入字母或数字prevent用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆