简体   繁体   English

C ++上的整数验证

[英]Integer validation On C++

I have written small C++ console application and this is source code : 我已经编写了小型C ++控制台应用程序,这是源代码:

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

void main()
{
    setlocale(LC_ALL, "turkish");
    int a,b,c,d;

    printf("first number: ");
    scanf("%d", &a);

    printf("second number: ");
    scanf("%d", &b);

    c = a+b;

    printf("Sum: : %d\n", c);
}

As you can see i'm requesting two numbers from user and than summing them. 如您所见,我正在向用户请求两个数字,而不是求和。 But i want to add a control which check number who enterede by user is integer? 但是我想添加一个控件,哪个用户输入的支票号码是整数?

I'll check number which typed by user and than if number isn't really a integer i will echo an error. 我将检查由用户键入的数字,如果数字不是真正的整数,我将回显错误。 I'm using this after every scanf but it's not working very well. 我在每次scanf之后都使用它,但是效果不是很好。

if(!isdigit(a))
{
            printf("Invalid Char !");
            exit(1);
}

In shortly, on a scanf action, if user type "a" it will produce an error message and program stop working. 简而言之,在scanf动作中,如果用户键入“ a”,将产生错误消息,程序停止运行。 If user type a number program will continue 如果用户键入数字程序将继续

scanf does that validation for you. scanf为您执行该验证。 Just check the return value from scanf . 只需检查scanf的返回值即可。

printf("first number: ");
if(scanf("%d", &a) != 1) {
  printf("Bad input\n");
  return 1;
}

printf("second number: ");
if(scanf("%d", &b) != 1) {
  printf("Bad input\n");
  return 1;
}

The C++ way to do this would be C ++的方法是

#include <iostream>
#include <locale>

int main()
{
    std::locale::global(std::locale("nl_NL.utf8")); // tr_TR doesn't exist on my system

    std::cout << "first number: ";

    int a;
    if (!(std::cin >> a))
    {
        std::cerr << "whoops" << std::endl;
        return 255;
    }

    std::cout << "second number: ";

    int b;
    if (!(std::cin >> b))
    {
        std::cerr << "whoops" << std::endl;
        return 255;
    }

    int c = a+b;

    std::cout << "Sum: " <<  c << std::endl;

    return 0;
}

isdigit takes a char as an argument. isdigitchar作为参数。

If the call to scanf succeeds, you're guaranteed that you have an integer. 如果对scanf的调用成功,则可以确保您有一个整数。

scanf also has a return value which indicates how many values it has read. scanf还具有一个返回值,该值指示已读取多少个值。

You want to check if the return value of scanf is 1 in this case. 在这种情况下,您要检查scanf的返回值是否为1。

See: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/ 请参阅: http : //www.cplusplus.com/reference/clibrary/cstdio/scanf/

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

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