-4

I try to use this code

#include <stdio.h>
int main() {
    int x,y,z;

    scanf("%d%d", &x, &y);
    z = x + y;
    printf("%d", z);
    return 0;
}

The problem is: Two man have x and y dollar. Take input of x(0 < x < 10000) and y(0 < y < 10000) and print the summation of their dollars.

hellow
  • 12,430
  • 7
  • 56
  • 79
  • 2
    I don't know any library that do it, C don't have this kind of feature you must do it yourself. – Stargateur Oct 09 '18 at 14:05
  • That is called parsing and is not something very easy in C... you have to take in a string instead of an integer in that case... Also, please rectify the question to make it more clear since I still don't understand your question. – Ruks Oct 09 '18 at 14:07
  • 1
    If I have understand, you want `x > 0` and `x < 100` ? If `x` isn't in this range what your program should do ? – Loufi Oct 09 '18 at 14:08
  • 2
    What is your actual problem? We don't write code for you, but instead help you to solve your errors. Please read [How to ask](https://stackoverflow.com/help/how-to-ask) and stay [on topic](https://stackoverflow.com/help/on-topic) – hellow Oct 09 '18 at 14:16

3 Answers3

2

You cannot put restriction on user entering any value. But you can ask user to re-enter the values again in specified limit with little modification in your code.

scanf("%d%d", &x, &y);
while( x <= 0 || y <= 0 || x >= 10000 || y >= 10000) {
    // Suitable message for re-entry of numbers.
    scanf("%d%d", &x, &y);
}
z = x + y;
printf("%d", z);
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Shravan40
  • 8,922
  • 6
  • 28
  • 48
1

There's no standard way to do a range check as part of an input operation in C - IOW, you can't tell scanf to reject an integer input that's outside of a specific range. You will have to add a range check separately:

if ( scanf( "%d%d", &x, &y ) == 2 ) // make sure both x and y are read
{
  if ( 0 < x && x < 1000 && 0 < y && y < 1000 )
  {
    z = x + y;
    printf( "z = %d\n", z );
  }
  else
  {
    printf( "Both x and y must be between 0 and 1000\n" );
  }
}
else
{
  printf( "At least one bad input for x or y\n" );
}
John Bode
  • 119,563
  • 19
  • 122
  • 198
0

You cannot restrict scanf to not to get an undesired integer, but you can re-take the input from the user if the value entered is bigger than 10k or smaller than 0. That would be a simple solution.

scanf("%d%d", &x, &y);

if( x > 10000 || x <= 0) {
 printf("Please re-enter a value for x: \n");
 scanf("%d", &x);
 }

if( y > 10000 || y <= 0) {
 printf("Please re-enter a value for y: \n");
 scanf("%d", &y);
 }

If you want you can also make a termination scenario by using "End of File" (EOF). Putting this here for source. How to use EOF

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Belverus
  • 623
  • 6
  • 10