473,385 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Can't figure out why scanf does this

Hello

Just to let you know this not homework, I'm learning the language of C
on my own time..

I recently tried to create a escape for user saying
printf ("Do you want to continue? (y or n)");
The scanf statement follows the prompt(printf above) which is the last
statement in the while loop, before the "}"

This scanf statement doesn't work!!
scanf("%c", &answer); //answer is declared as char....OK

When I run the debugger in Turbo C++, it goes rate on by, and doesn't
stop to ask the user to enter a char 'y' or 'n'.......I spent an hour
trying to hault the program at the scanf statement.

What's going on here?

Then I tried this statement.........:)

scanf("\n%c", &answer); //Works!!, but I don't know why?

Can someone tell me? please..

-Neil
Thanks for all your help

Nov 18 '06 #1
8 2351
Neil wrote:
Hello

Just to let you know this not homework, I'm learning the language of C
on my own time..

I recently tried to create a escape for user saying
printf ("Do you want to continue? (y or n)");
The scanf statement follows the prompt(printf above) which is the last
statement in the while loop, before the "}"

This scanf statement doesn't work!!
scanf("%c", &answer); //answer is declared as char....OK

When I run the debugger in Turbo C++, it goes rate on by, and doesn't
stop to ask the user to enter a char 'y' or 'n'.......I spent an hour
trying to hault the program at the scanf statement.

What's going on here?
It probably has to do with stray input left over in the standard input
stream's internal buffers. These could be ordinary characters or
newlines or whitespace characters. When you call scanf(), it will read
in these characters and return before you want.

Try flushing the buffer with a custom function that uses getc() or
fgetc() or getchar() to read in unwanted input and discard them. Don't
use the fflush() function for input streams. It'll invoke undefined
behaviour.

A better strategy is to use a line oriented input function like fgets()
or the non-portable ggets(), (search this group for posts from
'CBFalconer' with 'ggets' as a keyword), to read in an entire line and
then use functions like sscanf(), strtoXX() family etc. to get what you
want. It's more work upfront, but pays off in the long term, since it's
more robust and flexible than scanf().

Nov 18 '06 #2

santosh wrote:
Neil wrote:
Hello

Just to let you know this not homework, I'm learning the language of C
on my own time..

I recently tried to create a escape for user saying
printf ("Do you want to continue? (y or n)");
The scanf statement follows the prompt(printf above) which is the last
statement in the while loop, before the "}"

This scanf statement doesn't work!!
scanf("%c", &answer); //answer is declared as char....OK

When I run the debugger in Turbo C++, it goes rate on by, and doesn't
stop to ask the user to enter a char 'y' or 'n'.......I spent an hour
trying to hault the program at the scanf statement.

What's going on here?

It probably has to do with stray input left over in the standard input
stream's internal buffers. These could be ordinary characters or
newlines or whitespace characters. When you call scanf(), it will read
in these characters and return before you want.

Try flushing the buffer with a custom function that uses getc() or
fgetc() or getchar() to read in unwanted input and discard them. Don't
use the fflush() function for input streams. It'll invoke undefined
behaviour.

A better strategy is to use a line oriented input function like fgets()
or the non-portable ggets(), (search this group for posts from
'CBFalconer' with 'ggets' as a keyword), to read in an entire line and
then use functions like sscanf(), strtoXX() family etc. to get what you
want. It's more work upfront, but pays off in the long term, since it's
more robust and flexible than scanf().
Thanks for your help, I'll do that...

-Neil.

Nov 18 '06 #3
santosh wrote:
Neil wrote:
>Hello

Just to let you know this not homework, I'm learning the language of C
on my own time..

I recently tried to create a escape for user saying
printf ("Do you want to continue? (y or n)");
printf ("Do you want to continue? (y or n)\n");

OR

printf ("Do you want to continue? (y or n)");
fflush(stdout);
>The scanf statement follows the prompt(printf above) which is the last
statement in the while loop, before the "}"

This scanf statement doesn't work!!
scanf("%c", &answer); //answer is declared as char....OK

When I run the debugger in Turbo C++, it goes rate on by, and doesn't
stop to ask the user to enter a char 'y' or 'n'.......I spent an hour
trying to hault the program at the scanf statement.

What's going on here?

It probably has to do with stray input left over in the standard input
stream's internal buffers. These could be ordinary characters or
newlines or whitespace characters. When you call scanf(), it will read
in these characters and return before you want.
Not exactly. The OP is omitting the terminating newline in the call to
printf and therefore the buffer is never getting flushed. In the above
scanf call, however, there will be a remaining newline on the stdin
stream and in the next call to scanf (or fgetc, etc) that newline will
be the first character read in.
>
Try flushing the buffer with a custom function that uses getc() or
fgetc() or getchar() to read in unwanted input and discard them. Don't
use the fflush() function for input streams. It'll invoke undefined
behaviour.

A better strategy is to use a line oriented input function like fgets()
or the non-portable ggets(), (search this group for posts from
'CBFalconer' with 'ggets' as a keyword), to read in an entire line and
then use functions like sscanf(), strtoXX() family etc. to get what you
want. It's more work upfront, but pays off in the long term, since it's
more robust and flexible than scanf().
I completely agree. Even a home-rolled function for this case would suffice.
Nov 18 '06 #4
On Fri, 2006-17-11 at 18:17 -0800, santosh wrote:
A better strategy is to use a line oriented input function like fgets()
or the non-portable ggets(), (search this group for posts from
'CBFalconer' with 'ggets' as a keyword), to read in an entire line and
then use functions like sscanf(), strtoXX() family etc. to get what you
want. It's more work upfront, but pays off in the long term, since it's
more robust and flexible than scanf().
I don't think that "non-portable" is an appropriate term: the function
is written in Standard C and available wherever you have an Internet
connection (or your friend has an Internet connection and you have a
diskette drive) (or a CD drive, a scanner, a network or a notebook).

--
Andrew Poelstra <http://www.wpsoftware.net>
For email, use [first_name].[last]@gmail.com
"You're only smart on the outside." -anon.

Nov 18 '06 #5
Andrew Poelstra wrote:
On Fri, 2006-17-11 at 18:17 -0800, santosh wrote:
A better strategy is to use a line oriented input function like fgets()
or the non-portable ggets(), (search this group for posts from
'CBFalconer' with 'ggets' as a keyword), to read in an entire line and
then use functions like sscanf(), strtoXX() family etc. to get what you
want. It's more work upfront, but pays off in the long term, since it's
more robust and flexible than scanf().

I don't think that "non-portable" is an appropriate term: the function
is written in Standard C and available wherever you have an Internet
connection (or your friend has an Internet connection and you have a
diskette drive) (or a CD drive, a scanner, a network or a notebook).
Yes. Apologies, I should've said 'non-standard'.

Nov 18 '06 #6
santosh said:

<snip>
It probably has to do with stray input left over in the standard input
stream's internal buffers. These could be ordinary characters or
newlines or whitespace characters. When you call scanf(), it will read
in these characters and return before you want.

Try flushing the buffer
To "flush the buffer" is an output operation, as the description of fflush
makes very clear. I know you're not suggesting that function should be used
(good!); but I think the expression itself is best reserved for uses where
fflush /is/ appropriate, of which this ain't one.

And what's this "stray input", anyway? I don't know about you, but I
consider my time to be sufficiently valuable that I don't waste it typing
stray input into a computer program. If I type the input, I darn well
expect the computer to process it; *I'll* be the judge of whether it's
relevant.

<snip>

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: normal service will be restored as soon as possible. Please do not
adjust your email clients.
Nov 18 '06 #7
trm
Neil schrieb:
I recently tried to create a escape for user saying
printf ("Do you want to continue? (y or n)");
The scanf statement follows the prompt(printf above) which is the
last statement in the while loop, before the "}"

This scanf statement doesn't work!!
scanf("%c", &answer); //answer is declared as char....OK

When I run the debugger in Turbo C++, it goes rate on by, and
doesn't stop to ask the user to enter a char 'y' or 'n'.......I spent
an hour trying to hault the program at the scanf statement.
As someone else already pointed out, the printf() might not be seen
if it isn't terminated by a newline, or followed by an fflush(stdout).
What's going on here?

Then I tried this statement.........:)

scanf("\n%c", &answer); //Works!!, but I don't know why?
Consider also:

scanf(" %c", &answer);
scanf("%1s", &answer);
scanf(" %1[ynYN]", &answer);

Study your documentation for scanf(). When you can explain why
these are equivalent for your example, you'll have a pretty good
understanding of the whole scanf() family, as well as why you don't
usually want to use scanf() for directly reading and parsing input.

Nov 19 '06 #8
trm wrote:
>
.... snip ...
>
Consider also:

scanf(" %c", &answer);
scanf("%1s", &answer);
scanf(" %1[ynYN]", &answer);

Study your documentation for scanf(). When you can explain why
these are equivalent for your example, you'll have a pretty good
understanding of the whole scanf() family, as well as why you don't
usually want to use scanf() for directly reading and parsing input.
Those statements are all flawed, in that they fail to check the
return value. A sin with scanf.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

Nov 19 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Intaek LIM | last post by:
Hello. I always used cin in C++ for standard input. But, with C, I must use scanf. Integers, chars are all fine with scanf. The problem is... I cannot read floating point value like 'double'...
8
by: Steve Zimmerman | last post by:
This post is not intended as an argument to any other post, just some simple scanf experiments that I wanted to share. I found experiments 5 and 6 the most educational. Also, I thought...
39
by: Teh Charleh | last post by:
OK I have 2 similar programmes, why does the first one work and the second does not? Basically the problem is that the program seems to ignore the gets call if it comes after a scanf call. Please...
14
by: Peter Mount | last post by:
Hello I'm having trouble with " scanf("%c", &answer);" on line 20 below. When I run the program in cygwin on Windows 98SE it skips that line completely and ends the program. Does scanf have...
7
by: hugo27 | last post by:
obrhy8 June 18, 2004 Most compilers define EOF as -1. I'm just putting my toes in the water with a student's model named Miracle C. The ..h documentation of this compiler does state that when...
15
by: | last post by:
In Stephen G. Kochan's book "Programming in C" there is a program with the following: for(i = 1; i <= numOfGrades; ++i) { printf("Enter grade #%i: ", i); scanf("i%", &grade); ... } Does...
6
by: obdict | last post by:
Hello, I used scanf() in a while loop, which ensures that user input is valid (must be an integer no greater than 21 or less than 3). If user enters a number out of the range, or enters...
15
by: E-Dot | last post by:
I am trying to write a program which asks the user to enter a number in the interval , the program then gives the natural logarithm of that number, using the series for log(x+1)... Here is what...
4
by: Mohd Azhar Hussain | last post by:
I am new to C. I was trying to read input from key board using scanf, here's my program int main(void) { int i,j; scanf("hai");
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.