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..

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 ..

Edited 5 Years Ago by WaltP: Fixed CODE tags. If your post looks bad, feel free to use the EDIT button.

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

Edited 5 Years Ago by WaltP: n/a

This article has been dead for over six months. Start a new discussion instead.