热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

检查输入是否为C中的整数类型-CheckifinputisintegertypeinC

ThecatchisthatIcannotuseatoioranyotherfunctionlikethat(Imprettysureweresupposed

The catch is that I cannot use atoi or any other function like that (I'm pretty sure we're supposed to rely on mathematical operations).

问题是我不能使用atoi或其他类似的函数(我很确定我们应该依赖于数学运算)。

 int num; 
 scanf("%d",&num);
 if(/* num is not integer */) {
  printf("enter integer");
  return;
 }

I've tried:

我试过了:

(num*2)/2 == num
num%1==0
if(scanf("%d",&num)!=1)

but none of these worked.

但这些都没有奏效。

Any ideas?

什么好主意吗?

13 个解决方案

#1


32  

num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).

num总是包含一个整数,因为它是一个整数。scanf返回已成功读取的项的数量,因此在这种情况下,它必须返回1作为有效值。如果没有,则输入一个无效的整数值,num变量可能不会被更改(也就是说,仍然有一个任意的值,因为您没有初始化它)。

As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d\n"), but here's a trick to do it:

在您的评论中,您只希望允许用户输入一个整数,后跟enter键。不幸的是,scanf(“%d\n”)不能简单地实现这一点,但是这里有一个技巧:

int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
    printf("failure\n");
else
    printf("valid integer followed by enter key\n");

#2


22  

You need to read your input as a string first, then parse the string to see if it contains valid numeric characters. If it does then you can convert it to an integer.

您需要首先将输入作为字符串读取,然后解析该字符串以查看它是否包含有效的数字字符。如果是的话,你可以把它转换成一个整数。

char s[MAX_LINE];

valid = FALSE;
fgets(s, sizeof(s), stdin);
len = strlen(s);
while (len > 0 && isspace(s[len - 1]))
    len--;     // strip trailing newline or other white space
if (len > 0)
{
    valid = TRUE;
    for (i = 0; i 

#3


12  

There are several problems with using scanf with the %d conversion specifier to do this:

使用%d转换说明符使用scanf有几个问题:

  1. If the input string starts with a valid integer (such as "12abc"), then the "12" will be read from the input stream and converted and assigned to num, and scanf will return 1, so you'll indicate success when you (probably) shouldn't;

    如果输入字符串以一个有效整数(如“12abc”)开始,那么将从输入流中读取“12”,并将其转换为num,而scanf将返回1,因此当您(可能)不应该时,您将指示成功;

  2. If the input string doesn't start with a digit, then scanf will not read any characters from the input stream, num will not be changed, and the return value will be 0;

    如果输入字符串不以数字开头,那么scanf将不会从输入流中读取任何字符,num将不会被更改,返回值将为0;

  3. You don't specify if you need to handle non-decimal formats, but this won't work if you have to handle integer values in octal or hexadecimal formats (0x1a). The %i conversion specifier handles decimal, octal, and hexadecimal formats, but you still have the first two problems.

    您不指定是否需要处理非十进制格式,但如果必须处理八进制或十六进制格式(0x1a)的整数值,则不能这样做。%i转换说明符处理十进制、八进制和十六进制格式,但是仍然存在前两个问题。

First of all, you'll need to read the input as a string (preferably using fgets). If you aren't allowed to use atoi, you probably aren't allowed to use strtol either. So you'll need to examine each character in the string. The safe way to check for digit values is to use the isdigit library function (there are also the isodigit and isxdigit functions for checking octal and hexadecimal digits, respectively), such as

首先,您需要将输入读取为字符串(最好使用fgets)。如果你不允许使用atoi,你可能也不允许使用strtol。因此,您需要检查字符串中的每个字符。检查数字值的安全方法是使用isdigit库函数(还有分别检查八进制和十六进制数字的isodigit和isxdigit函数),例如

while (*input && isdigit(*input))
   input++;    

(if you're not even allowed to use isdigit, isodigit, or isxdigit, then slap your teacher/professor for making the assignment harder than it really needs to be).

(如果你甚至都不允许使用isdigit、isodigit或isxdigit,那就扇你的老师/教授一巴掌,让你的作业比实际需要的更困难)。

If you need to be able to handle octal or hex formats, then it gets a little more complicated. The C convention is for octal formats to have a leading 0 digit and for hex formats to have a leading 0x. So, if the first non-whitespace character is a 0, you have to check the next character before you can know which non-decimal format to use.

如果您需要能够处理八进制或十六进制格式,那么它会变得有点复杂。C的约定是八进制格式的首位为0,十六进制格式的首位为0x。因此,如果第一个非空格字符是0,您必须先检查下一个字符,然后才能知道使用哪种非十进制格式。

The basic outline is

的基本轮廓

  1. If the first non-whitespace character is not a '-', '+', '0', or non-zero decimal digit, then this is not a valid integer string;
  2. 如果第一个非空白字符不是'-'、'+'、'0'或非零小数位数,那么这不是一个有效的整数字符串;
  3. If the first non-whitespace character is '-', then this is a negative value, otherwise we assume a positive value;
  4. 如果第一个非空白字符是'-',则这是一个负值,否则我们假定为正值;
  5. If the first character is '+', then this is a positive value;
  6. 如果第一个字符是'+',那么这是一个正值;
  7. If the first non-whitespace and non-sign character is a non-zero decimal digit, then the input is in decimal format, and you will use isdigit to check the remaining characters;
  8. 如果第一个非空格和非符号字符为非零小数位数,则输入为十进制格式,您将使用isdigit检查其余字符;
  9. If the first non-whitespace and non-sign character is a '0', then the input is in either octal or hexadecimal format;
  10. 如果第一个非空格和非符号字符为“0”,则输入为八进制或十六进制格式;
  11. If the first non-whitespace and non-sign character was a '0' and the next character is a digit from '0' to '7', then the input is in octal format, and you will use isodigit to check the remaining characters;
  12. 如果第一个非空格和非符号字符是“0”,而下一个字符是从“0”到“7”,则输入为八进制格式,您将使用isodigit检查其余字符;
  13. If the first non-whitespace and non-sign character was a 0 and the second character is x or X, then the input is in hexadecimal format and you will use isxdigit to check the remaining characters;
  14. 如果第一个非空格和非符号字符为0,第二个字符为x或x,则输入为十六进制格式,您将使用isxdigit检查其余字符;
  15. If any of the remaining characters do not satisfy the check function specified above, then this is not a valid integer string.
  16. 如果剩下的任何字符都不满足上面指定的check函数,那么这不是一个有效的整型字符串。

#4


4  

First ask yourself how you would ever expect this code to NOT return an integer:

首先问问你自己,你怎么能指望这段代码不返回一个整数:

int num; 
scanf("%d",&num);

You specified the variable as type integer, then you scanf, but only for an integer (%d).

您将变量指定为类型integer,然后使用scanf,但只针对整数(%d)。

What else could it possibly contain at this point?

在这一点上它还可能包含什么?

#5


0  

I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!

我查看了上面每个人的输入,这是非常有用的,并制作了一个适合我自己应用的函数。这个函数实际上只是评估用户的输入不是“0”,但它对我来说已经足够好了。希望这可以帮助!

#include

int iFunctErrorCheck(int iLowerBound, int iUpperBound){

int iUserInput=0;
while (iUserInput==0){
    scanf("%i", &iUserInput);
    if (iUserInput==0){
        printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
        getchar();
    }
    if ((iUserInput!=0) && (iUserInputiUpperBound)){
        printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
        iUserInput=0;
    }
}
return iUserInput;
}

#6


0  

Try this...

试试这个…

#include 

int main (void)
{
    float a;
    int q;

    printf("\nInsert number\t");
    scanf("%f",&a);

    q=(int)a;
    ++q;

    if((q - a) != 1)
        printf("\nThe number is not an integer\n\n");
    else
        printf("\nThe number is an integer\n\n");

    return 0;
}

#7


0  

This is a more user-friendly one I guess :

我想这是一个更友好的方法:

#include

/* This program checks if the entered input is an integer
 * or provides an option for the user to re-enter.
 */

int getint()
{
  int x;
  char c;
  printf("\nEnter an integer (say -1 or 26 or so ): ");
  while( scanf("%d",&x) != 1 )
  {
    c=getchar();

    printf("You have entered ");
    putchar(c);
    printf(" in the input which is not an integer");

    while ( getchar() != '\n' )
     ; //wasting the buffer till the next new line

    printf("\nEnter an integer (say -1 or 26 or so ): ");

  }

return x;
}


int main(void)
{
  int x;
  x=getint();

  printf("Main Function =>\n");
  printf("Integer : %d\n",x);

 return 0;
}

#8


0  

I developed this logic using gets and away from scanf hassle:

我使用get and away from scanf麻烦开发了这个逻辑:

void readValidateInput() {

    char str[10] = { '\0' };

    readStdin: fgets(str, 10, stdin);
    //printf("fgets is returning %s\n", str);

    int numerical = 1;
    int i = 0;

    for (i = 0; i <10; i++) {
        //printf("Digit at str[%d] is %c\n", i, str[i]);
        //printf("numerical = %d\n", numerical);
        if (isdigit(str[i]) == 0) {
            if (str[i] == '\n')break;
            numerical = 0;
            //printf("numerical changed= %d\n", numerical);
            break;
        }
    }
    if (!numerical) {
        printf("This is not a valid number of tasks, you need to enter at least 1 task\n");
        goto readStdin;
    }
    else if (str[i] == '\n') {
        str[i] = '\0';
        numOfTasks = atoi(str);
        //printf("Captured Number of tasks from stdin is %d\n", numOfTasks);
    }
}

#9


0  

printf("type a number ");
int cOnverted= scanf("%d", &a);
printf("\n");

if( cOnverted== 0) 
{
    printf("enter integer");
    system("PAUSE \n");
    return 0;
}

scanf() returns the number of format specifiers that match, so will return zero if the text entered cannot be interpreted as a decimal integer

scanf()返回匹配的格式说明符的数量,如果输入的文本不能解释为十进制整数,则返回0

#10


-1  

I was having the same problem, finally figured out what to do:

我遇到了同样的问题,终于想出了办法:

#include 
#include 

int main ()
{
    int x;
    float check;
    reprocess:
    printf ("enter a integer number:");
    scanf ("%f", &check);
    x=check;
    if (x==check)
    printf("\nYour number is %d", x);
    else 
    {
         printf("\nThis is not an integer number, please insert an integer!\n\n");
         goto reprocess;
    }
    _getch();
    return 0;
}

#11


-1  

I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.

我一直在寻找一个更简单的解决方案,只使用循环和if语句,这就是我想到的。该程序还可以处理负整数,并正确地拒绝任何可能包含整数和其他字符的混合输入。


#include 
#include  // Used for atoi() function
#include  // Used for strlen() function

#define TRUE 1
#define FALSE 0

int main(void)
{
    char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
    int intTest;
    printf("Give me an int: ");

    do
    {        
        scanf(" %s", n);

        intTest = TRUE; // Sets the default for the integer test variable to TRUE

        int i = 0, l = strlen(n);
        if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
            i++;
        while (i  '9') // Tests the string characters for non-integer values
            {              
                intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
                break;
            }
            i++;
        }
        if (intTest == TRUE)
            printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
        else
            printf("Retry: "); // Prints "Retry:" if tested FALSE
    }
    while (intTest == FALSE); // Continues to ask the user to input a valid integer value
    return 0;
}

#12


-1  

This method works for everything (integers and even doubles) except zero (it calls it invalid):

此方法适用于除零(它称其为无效)之外的所有事物(整数甚至双数):

The while loop is just for the repetitive user input. Basically it checks if the integer x/x = 1. If it does (as it would with a number), its an integer/double. If it doesn't, it obviously it isn't. Zero fails the test though.

while循环仅用于重复的用户输入。它检查整数x/x是否等于1。如果它这样做(就像它对待数字那样),它就是一个整数/双精度数。如果没有,显然不是。Zero在测试中失败了。

#include  
#include 

void main () {
    double x;
    int notDouble;
    int true = 1;
    while(true) {
        printf("Input an integer: \n");
        scanf("%lf", &x);
        if (x/x != 1) {
            notDouble = 1;
            fflush(stdin);
        }
        if (notDouble != 1) {
            printf("Input is valid\n");
        }
        else {
            printf("Input is invalid\n");
        }
        notDouble = 0;
    }
}

#13


-2  

I found a way to check whether the input given is an integer or not using atoi() function .

我找到了一种方法,可以使用atoi()函数检查给定的输入是否是整数。

Read the input as a string, and use atoi() function to convert the string in to an integer.

将输入读取为字符串,并使用atoi()函数将字符串转换为整数。

atoi() function returns the integer number if the input string contains integer, else it will return 0. You can check the return value of the atoi() function to know whether the input given is an integer or not.

函数的作用是:如果输入字符串包含整数,则返回整数,否则返回0。您可以检查atoi()函数的返回值,以知道给定的输入是否是整数。

There are lot more functions to convert a string into long, double etc., Check the standard library "stdlib.h" for more.

还有很多函数可以将字符串转换为长、双等,请查看标准库“stdlib”。h”。

Note : It works only for non-zero numbers.

注意:它只适用于非零数。

#include
#include

int main() {
    char *string;
    int number;

    printf("Enter a number :");
    scanf("%s", string);

    number = atoi(string);

    if(number != 0)
        printf("The number is %d\n", number);
    else
        printf("Not a number !!!\n");
    return 0;
}

推荐阅读
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • Week04面向对象设计与继承学习总结及作业要求
    本文总结了Week04面向对象设计与继承的重要知识点,包括对象、类、封装性、静态属性、静态方法、重载、继承和多态等。同时,还介绍了私有构造函数在类外部无法被调用、static不能访问非静态属性以及该类实例可以共享类里的static属性等内容。此外,还提到了作业要求,包括讲述一个在网上商城购物或在班级博客进行学习的故事,并使用Markdown的加粗标记和语句块标记标注关键名词和动词。最后,还提到了参考资料中关于UML类图如何绘制的范例。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 本文介绍了Java高并发程序设计中线程安全的概念与synchronized关键字的使用。通过一个计数器的例子,演示了多线程同时对变量进行累加操作时可能出现的问题。最终值会小于预期的原因是因为两个线程同时对变量进行写入时,其中一个线程的结果会覆盖另一个线程的结果。为了解决这个问题,可以使用synchronized关键字来保证线程安全。 ... [详细]
  • 标题: ... [详细]
  • C++字符字符串处理及字符集编码方案
    本文介绍了C++中字符字符串处理的问题,并详细解释了字符集编码方案,包括UNICODE、Windows apps采用的UTF-16编码、ASCII、SBCS和DBCS编码方案。同时说明了ANSI C标准和Windows中的字符/字符串数据类型实现。文章还提到了在编译时需要定义UNICODE宏以支持unicode编码,否则将使用windows code page编译。最后,给出了相关的头文件和数据类型定义。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • 纠正网上的错误:自定义一个类叫java.lang.System/String的方法
    本文纠正了网上关于自定义一个类叫java.lang.System/String的错误答案,并详细解释了为什么这种方法是错误的。作者指出,虽然双亲委托机制确实可以阻止自定义的System类被加载,但通过自定义一个特殊的类加载器,可以绕过双亲委托机制,达到自定义System类的目的。作者呼吁读者对网上的内容持怀疑态度,并带着问题来阅读文章。 ... [详细]
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • 本文介绍了MVP架构模式及其在国庆技术博客中的应用。MVP架构模式是一种演变自MVC架构的新模式,其中View和Model之间的通信通过Presenter进行。相比MVC架构,MVP架构将交互逻辑放在Presenter内部,而View直接从Model中读取数据而不是通过Controller。本文还探讨了MVP架构在国庆技术博客中的具体应用。 ... [详细]
author-avatar
亦涵Doris
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有