繁体   English   中英

检查输入是否为 integer 输入 C

[英]Check if input is integer type in C

问题是我不能像那样使用 atoi 或任何其他 function(我很确定我们应该依赖数学运算)。

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

我试过了:

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

但这些都不起作用。

有任何想法吗?

num将始终包含一个整数,因为它是一个int 您的代码的真正问题在于您没有检查scanf返回值。 scanf返回成功读取的项目数,因此在这种情况下,它必须为有效值返回 1。 如果不是,则输入了无效的整数值,并且num变量可能没有更改(即仍然具有任意值,因为您没有对其进行初始化)。

根据您的评论,您只想允许用户输入一个整数,后跟 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");

您需要先将输入作为字符串读取,然后解析该字符串以查看它是否包含有效的数字字符。 如果是,那么您可以将其转换为整数。

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

使用带有%d转换说明符的scanf来执行此操作有几个问题:

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

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

  3. 您没有指定是否需要处理非十进制格式,但如果您必须处理八进制或十六进制格式 (0x1a) 的整数值,这将不起作用。 %i转换说明符处理十进制、八进制和十六进制格式,但您仍然有前两个问题。

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

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

(如果你甚至不被允许使用isdigitisodigitisxdigit ,那么你的老师/教授让作业变得比实际需要的更难)。

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

基本轮廓是

  1. 如果第一个非空白字符不是“-”、“+”、“0”或非零十进制数字,则这不是有效的整数字符串;
  2. 如果第一个非空白字符是“-”,那么这是一个负值,否则我们假设一个正值;
  3. 如果第一个字符是“+”,那么这是一个正值;
  4. 如果第一个非空格和非符号字符是非零十进制数字,则输入是十进制格式,您将使用isdigit来检查剩余的字符;
  5. 如果第一个非空白和非符号字符是“0”,则输入是八进制或十六进制格式;
  6. 如果第一个非空白和非符号字符是 '0',下一个字符是从 '0' 到 '7' 的数字,则输入是八进制格式,您将使用isodigit检查其余字符;
  7. 如果第一个非空格和非符号字符是 0,第二个字符是xX ,则输入是十六进制格式,您将使用isxdigit来检查剩余的字符;
  8. 如果任何剩余字符不满足上面指定的检查函数,则这不是有效的整数字符串。

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

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

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

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

如果其他人提出这个问题,我已经编写了一个程序,它不断要求输入一个数字,如果用户的输入不是整数,并在接受一个整数时完成

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

上面看了大家的意见,很有用,做了一个适合自己应用的函数。 该函数实际上只是评估用户的输入不是“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;
}

试试这个...

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

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

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

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

我解决这个问题的方法是使用 cs50.h 库。 所以,header 是这样的:

#include <cs50.h>

你有 get_int function 并且你只需将它用于变量初始化:

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

如果用户输入的不是 integer,则 output 会重复“您的号码是:”这一行; 依此类推,直到写入 integer。

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


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

只需检查您的号码与它的浮动版本是否有任何区别。

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

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

此方法适用于除零之外的所有内容(整数甚至双精度数)(它称之为无效):

while 循环仅用于重复的用户输入。 基本上它检查整数 x/x = 1。如果它是(就像使用数字一样),它是一个整数/双精度数。 如果不是,那显然不是。 零虽然没有通过测试。

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

我遇到了同样的问题,终于想出了该怎么做:

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

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

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

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

将字符串转换为 long、double 等的函数还有很多,请查看标准库“stdlib.h”了解更多信息。

注意:它仅适用于非零数字。

#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