• C

scanf and new line character

scanf("%i", &n);

 where n has been declared: int n;

 my problem is that when it asks me to enter an integer, it reads the newline character as well. Since it doesn't match it puts it back fot the next scanf..
 How can avoid this without using another variable just to read the newline character?
anemosAsked:
Who is Participating?
 
Alien_SMConnect With a Mentor Commented:
There is an easy way to flush the input buffer using
int fflush(FILE *stream);

in the stdio.h unit

fflush(stdin);
works fine for flushing the input buffer of the keyboard
0
 
HardawayCommented:
The task is about getting integer numbers one-by-one in a loop? So that you would like to avoid the newline character?

Have you tried gets()? It was more useful in most cases. However, gets only support characters, you might need to do some conversion for getting integers.
0
 
anemosAuthor Commented:
how can I convert then the string into an integer??
I spse that means accesing each indvidual character.. there must be a more simple way..
0
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

 
ozoCommented:
What's the next scanf?  You can supress assignment with %*
0
 
arnondCommented:
if every line contains only one int followed by '\n', why not use:
char eol;
int n;
.......
.......
.......
scanf ("%i %c",&n,%eol);
......
......
......


and just ignore the eol.

Arnon David.

0
 
ntdragonCommented:
in scanf for integer try "%d"
or try to flash the input buffer
about the string to integer there is a func named atoi(...);
0
 
anemosAuthor Commented:
how do I flush the input buffer??
0
 
ntdragonCommented:
i didn't try to do that so you"ll have to check the help

but try to use _flushall();
0
 
ntdragonCommented:
good that there is ppl with a memory better then mine:>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.