Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Easy. C programming question

Status
Not open for further replies.

spitso

Member
Hi all

Just writing up some code, so far it all works perfectly until i accidentally enter a character (instead of an interger) for scanf.
It displays the menu over and over and over.....

Any ideas how i can get rid of this bug?
Im a beginner so i'd appreciate something as simplistic as possible.

Thankyou

attached is the code
 

Attachments

  • Untitled.png
    Untitled.png
    22.8 KB · Views: 324
There is a function in C called " isadigit() " so first call scanf for a character "%c" then check if its a digit then convert to an int (atoi());

Code:
char key;

if(isadigit(scanf("%c",key)))
   {
   process here;
   }
else
   dont;

something like this

Ian

OR.... just check that the scaned value is between 0 and 9.. (that's simpler)
 
Last edited:
The problem with "scanf" is that it leaves junk lying around in the buffer. If your menu is constantly being displayed, this might be the reason. Make a function like the one below, and call after the scanf line:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

...


void eat_junk(void) (
  int ch;

  while((ch = getchar()) != '\n') {
     if (ch < 0)
        exit(EXIT_FAILURE); //EOF!
  }
}

Find more information here : c - How to prevent the user from entering more data than the maximum limit? - Stack Overflow
 
thanks Ian

i tried checking the scanned value to see if its between 0 to 9, but if a character is press and it reloops.........its as if the programs skipping the scanf code and is just remembering what i had previously entered.

any ideas?
 
Thanks for that

Im guessing the " ( " after (void) is mean't to be " { ".

also sorry for a million question but as i said im a beginner.
What would be the code to call this function, so i can put it after my scanf() statement?

thanks in advance
 
Thanks for that

Im guessing the " ( " after (void) is mean't to be " { ".

That's correct.

What would be the code to call this function, so i can put it after my scanf() statement?

scanf(.....);
eat_junk();
....

You can get some of answers from the web page I linked.
 
Status
Not open for further replies.

New Articles From Microcontroller Tips

Back
Top