Hi,

As said in the title, the program needs to accept only integer values.. It should not accept float point numbers or characters or spaces or integers mixed with characters .. I know it has to do something with the while statement but i cant figure it out .. Your help will be greatly appreciated .. thanks in advance :)

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

  int get_int(int *px){
  scanf("%d",px);
  while (!scanf("%d",px)&& !isspace()&& getchar()!= '\n'){
    printf("Please enter an integer value:"); 
  }
 }
   
int main(int argc, const char *argv[]){
  int x,i;
  printf("Please enter a number:\n");
  get_int(&x);
  //for (i=0; i <20; i++)
   printf("you input the value: %d\n",x);
   fflush(stdin);
}

The program should have/achieve the following output:
prompt$ ./a.out
Please enter a number: asdf
please enter an integer value: 12.3
please enter an integer value: 12ab321
please enter an integer value: 12321
You input the value: 12321
prompt$


- thanks..

Akshay_18 commented: what if we enter "a55" +0

Recommended Answers

All 3 Replies

Take in your number as a string using fgets and check the string for good characters (characters from '0' to '9').

fflush(stdin);

Take a look at the links in http://www.daniweb.com/code/snippet217396.html to see why that is not a good idea.

Thanks .. it worked :) i still used scanf to get the input .. this is what i did .

ioInt = scanf("%d", pInput); // returns 1 if successfull 
    if(ioInt !=1){
      printf("\n Please enter an integer value:");
      while ((ioChar = getchar())!= '\n');

thanks again ..

So with your new and improved code, how do you pass the integer back to main() ? I think jonsca's idea is best.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.