C语言 检查输入是否为 C 中的整数类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4072190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:52:58  来源:igfitidea点击:

Check if input is integer type in C

cinputinteger

提问by Gal

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?

有任何想法吗?

回答by AndiDog

numwill always contain an integer because it's an int. The realproblem with your code is that you don't check the scanfreturn value. scanfreturns 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 numvariable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).

num将始终包含一个整数,因为它是一个int. 您的代码的真正问题在于您没有检查scanf返回值。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");

回答by Paul R

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 < len; ++i)
    {
        if (!isdigit(s[i]))
        {
            valid = FALSE;
            break;
        }
    }
}

回答by John Bode

There are several problems with using scanfwith the %dconversion specifier to do this:

有几个问题与使用scanf%d转换说明这样做:

  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 scanfwill return 1, so you'll indicate success when you (probably) shouldn't;

  2. If the input string doesn'tstart with a digit, then scanfwill not read anycharacters from the input stream, numwill not be changed, and the return value will be 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 %iconversion specifier handles decimal, octal, and hexadecimal formats, but you still have the first two problems.

  1. 如果输入字符串以有效整数开头(例如“12abc”),则将从输入流中读取“12”并转换并分配给numscanf并将返回 1,因此当您(可能) ) 不应该;

  2. 如果输入字符串以数字开头,则scanf不会从输入流中读取任何字符,num不会改变,返回值为0;

  3. 您没有指定是否需要处理非十进制格式,但如果您必须处理八进制或十六进制格式 (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 strtoleither. So you'll need to examine each character in the string. The safe way to check for digit values is to use the isdigitlibrary function (there are also the isodigitand isxdigitfunctions for checking octal and hexadecimal digits, respectively), such as

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

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 0digit 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. If the first non-whitespace character is '-', then this is a negative value, otherwise we assume a positive value;
  3. If the first character is '+', then this is a positive value;
  4. 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 isdigitto check the remaining characters;
  5. If the first non-whitespace and non-sign character is a '0', then the input is in either octal or hexadecimal format;
  6. 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 isodigitto check the remaining characters;
  7. If the first non-whitespace and non-sign character was a 0 and the second character is xor X, then the input is in hexadecimal format and you will use isxdigitto check the remaining characters;
  8. If any of the remaining characters do not satisfy the check function specified above, then this is not a valid integer string.
  1. 如果第一个非空白字符不是“-”、“+”、“0”或非零十进制数字,则这不是有效的整数字符串;
  2. 如果第一个非空白字符是“-”,那么这是一个负值,否则我们假设一个正值;
  3. 如果第一个字符是“+”,那么这是一个正值;
  4. 如果第一个非空格和非符号字符是非零十进制数字,则输入为十进制格式,您将用于isdigit检查剩余字符;
  5. 如果第一个非空白和非符号字符是“0”,则输入是八进制或十六进制格式;
  6. 如果第一个非空格和非符号字符是'0',下一个字符是'0'到'7'之间的数字,那么输入是八进制格式,您将用于isodigit检查剩余的字符;
  7. 如果第一个非空白和非符号字符是 0,第二个字符是xX,则输入是十六进制格式,您将用于isxdigit检查剩余的字符;
  8. 如果任何剩余字符不满足上面指定的检查函数,则这不是有效的整数字符串。

回答by abelenky

First ask yourself how you would everexpect this code to NOTreturn an integer:

首先问自己你将如何以往任何时候都希望这个代码返回一个整数:

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

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

您将变量指定为整数类型,然后您scanf,但适用于整数 ( %d)。

What else could it possibly contain at this point?

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

回答by Nick

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<stdio.h>

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) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
        printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
        iUserInput=0;
    }
}
return iUserInput;
}

回答by OscaRoCa

Try this...

尝试这个...

#include <stdio.h>

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;
}

回答by sjsam

This is a more user-friendly one I guess :

我猜这是一个更用户友好的:

#include<stdio.h>

/* 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;
}

回答by Shaimaa Yehia

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

我使用gets和远离scanf麻烦开发了这个逻辑:

void readValidateInput() {

    char str[10] = { '
printf("type a number ");
int converted = scanf("%d", &a);
printf("\n");

if( converted == 0) 
{
    printf("enter integer");
    system("PAUSE \n");
    return 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] = '
#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // 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 < l)
        {            
            if (n[i] < '0' || n[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;
}
'; numOfTasks = atoi(str); //printf("Captured Number of tasks from stdin is %d\n", numOfTasks); } }

回答by Eduardo

##代码##

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() 返回匹配的格式说明符的数量,因此如果输入的文本不能解释为十进制整数,则返回零

回答by de3z1e

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 语句的更简单的解决方案,这就是我想出的。该程序还可以处理负整数,并正确拒绝可能包含整数和其他字符的任何混合输入。



##代码##