#How to restrict input to integer only?

9 messages · Page 1 of 1 (latest)

granite tinsel
#

I have a c program where the user is asked to input numbers as data. How can I restrict the user inputs to number only and how to prevent the program from misbehaving if any special character or non integer input is given?

void insert(){
  int data; 
  printf("ENTER DATA: ");
  struct node *block = (struct node*)malloc(sizeof(struct node));
  scanf("%d",&data);
  block->data = data;
  block->link = head;
  head = block;
}

In the above function if the user enters any non integer character the programs just goes into infinite loop printing the print statement.

faint ridgeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

jade falcon
#

Don't ignore the return code from scanf() is the first step.

#

You could ofc link with cs50.
That gives you functions like get_int() which takes care of all this.

unique condor
#

One option is to read entire lines - and then perform secanf to parse them

granite tinsel
granite tinsel
faint ridgeBOT
#

@granite tinsel Has your question been resolved? If so, run !solved :)

granite tinsel
#

!solved