Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

c - How to test input is sane

Consider the following simple C program.

//C test

#include<stdio.h>

int main()
{
   int a, b, c;

   printf("Enter two numbers to add
");
   scanf("%d%d",&a,&b);

   c = a + b;
   printf("Sum of entered numbers = %d
",c);
   return 0;
}

How do you check the values entered are actually two integers in some sensible range? Currently, if you just enter "a" and then return you get the output "Sum of entered numbers = 32767".

Examples of incorrect input I would like to prevent.

  1. 2 3 4 (wrong number of numbers)
  2. apple (not a number)
  3. 11111111111111111111111111 1111111111111111111111111111111111111 (numbers out of range)

Or should I be using fgets and sscanf or even strtol ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use like:

if( scanf("%d%d",&a,&b) == 2)
{
   //two integer values has been read successfully
   //do your stuff here
}
else
{
   //Wrong input
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...