简体   繁体   English

检查输入是否为 integer 输入 C

[英]Check if input is integer type in C

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 或任何其他 function(我很确定我们应该依赖数学运算)。

 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?有任何想法吗?

num will always contain an integer because it's an int . num将始终包含一个整数,因为它是一个int The real problem with your code is that you don't check the scanf return value.您的代码的真正问题在于您没有检查scanf返回值。 scanf returns the number of successfully read items, so in this case it must return 1 for valid values. scanf返回成功读取的项目数,因此在这种情况下,它必须为有效值返回 1。 If not, an invalid integer value was entered and the num variable did probably not get changed (ie still has an arbitrary value because you didn't initialize it).如果不是,则输入了无效的整数值,并且num变量可能没有更改(即仍然具有任意值,因为您没有对其进行初始化)。

As of your comment, you only want to allow the user to enter an integer followed by the enter key.根据您的评论,您只想允许用户输入一个整数,后跟 Enter 键。 Unfortunately, this can't be simply achieved by scanf("%d\\n") , but here's a trick to do it:不幸的是,这不能简单地通过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");

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

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).您没有指定是否需要处理非十进制格式,但如果您必须处理八进制或十六进制格式 (0x1a) 的整数值,这将不起作用。 The %i conversion specifier handles decimal, octal, and hexadecimal formats, but you still have the first two problems. %i转换说明符处理十进制、八进制和十六进制格式,但您仍然有前两个问题。

First of all, you'll need to read the input as a string (preferably using fgets ).首先,您需要将输入作为字符串读取(最好使用fgets )。 If you aren't allowed to use atoi , you probably aren't allowed to use strtol either.如果不允许使用atoi ,则可能也不允许使用strtol 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检查数字值的安全方法是使用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). (如果你甚至不被允许使用isdigitisodigitisxdigit ,那么你的老师/教授让作业变得比实际需要的更难)。

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 . C 约定是八进制格式有一个前导0数字和十六进制格式有一个前导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.因此,如果第一个非空白字符是 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;如果第一个非空白字符不是“-”、“+”、“0”或非零十进制数字,则这不是有效的整数字符串;
  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 isdigit to check the remaining characters;如果第一个非空格和非符号字符是非零十进制数字,则输入是十进制格式,您将使用isdigit来检查剩余的字符;
  5. If the first non-whitespace and non-sign character is a '0', then the input is in either octal or hexadecimal format;如果第一个非空白和非符号字符是“0”,则输入是八进制或十六进制格式;
  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 isodigit to check the remaining characters;如果第一个非空白和非符号字符是 '0',下一个字符是从 '0' 到 '7' 的数字,则输入是八进制格式,您将使用isodigit检查其余字符;
  7. 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;如果第一个非空格和非符号字符是 0,第二个字符是xX ,则输入是十六进制格式,您将使用isxdigit来检查剩余的字符;
  8. If any of the remaining characters do not satisfy the check function specified above, then this is not a valid integer string.如果任何剩余字符不满足上面指定的检查函数,则这不是有效的整数字符串。

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 ).您将变量指定为整数类型,然后您scanf ,但适用于整数( %d )。

What else could it possibly contain at this point?在这一点上,它还可能包含什么?

If anyone else comes up with this question, i've written a program, that keeps asking to input a number, if user's input is not integer, and finishes when an integer number is accepted如果其他人提出这个问题,我已经编写了一个程序,它不断要求输入一个数字,如果用户的输入不是整数,并在接受一个整数时完成

#include<stdlib.h>
#include<stdio.h>
#include<stdbool.h>

bool digit_check(char key[])
{
    for(int i = 0; i < strlen(key); i++)
    {
        if(isdigit(key[i])==0)
        {
            return false;
        }
    }
    return true;
}

void main()
{
    char stroka[10];
    do{
        printf("Input a number: ");
        scanf("%s",stroka);}
    while (!digit_check(stroka));
    printf("Number is accepted, input finished!\n");
    system("pause");
}

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.该函数实际上只是评估用户的输入不是“0”,但对于我的目的来说已经足够了。 Hope this helps!希望这有帮助!

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

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

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

I developed this logic using gets and away from scanf hassle:我使用gets和远离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);
    }
}
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() 返回匹配的格式说明符的数量,因此如果输入的文本不能解释为十进制整数,则返回零

The way I worked around this question was using cs50.h library.我解决这个问题的方法是使用 cs50.h 库。 So, the header goes:所以,header 是这样的:

#include <cs50.h>

There you have get_int function and you simply use it for variable initiation:你有 get_int function 并且你只需将它用于变量初始化:

    int a = get_int("Your number is: "); 

If a user inputs anything but integer, output repeats the line "Your number is: ";如果用户输入的不是 integer,则 output 会重复“您的号码是:”这一行; and so on until the integer is being written.依此类推,直到写入 integer。

I've been searching for a simpler solution using only loops and if statements, and this is what I came up with.我一直在寻找只使用循环和 if 语句的更简单的解决方案,这就是我想出的。 The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.该程序还可以处理负整数,并正确拒绝可能包含整数和其他字符的任何混合输入。


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

Just check is your number has any difference with float version of it, or not.只需检查您的号码与它的浮动版本是否有任何区别。

float num; 
scanf("%f",&num);

if(num != (int)num) {
    printf("it's not an integer");
    return;
}

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. while 循环仅用于重复的用户输入。 Basically it checks if the integer x/x = 1. If it does (as it would with a number), its an integer/double.基本上它检查整数 x/x = 1。如果它是(就像使用数字一样),它是一个整数/双精度数。 If it doesn't, it obviously it isn't.如果不是,那显然不是。 Zero fails the test though.零虽然没有通过测试。

#include <stdio.h> 
#include <math.h>

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

I was having the same problem, finally figured out what to do:我遇到了同样的问题,终于想出了该怎么做:

#include <stdio.h>
#include <conio.h>

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

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.如果输入字符串包含整数,atoi() 函数返回整数,否则返回0。您可以检查atoi() 函数的返回值以了解给定的输入是否为整数。

There are lot more functions to convert a string into long, double etc., Check the standard library "stdlib.h" for more.将字符串转换为 long、double 等的函数还有很多,请查看标准库“stdlib.h”了解更多信息。

Note : It works only for non-zero numbers.注意:它仅适用于非零数字。

#include<stdio.h>
#include<stdlib.h>

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

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

    number = atoi(string);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM