I have written small C++ console application and this is source code :
#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 i开发者_如何学Gof 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.
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. If user type a number program will continue
scanf
does that validation for you. Just check the return value from 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
#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.
If the call to scanf
succeeds, you're guaranteed that you have an integer.
scanf
also has a return value which indicates how many values it has read.
You want to check if the return value of scanf
is 1 in this case.
See: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
精彩评论