473,883 Members | 2,819 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

scanf problem

I know this is the problem that most newbies get into.

#include<stdio. h>
int main(void)
{
char a;
scanf("%c",&a); /*1st scanf */
printf("%c\n",a );
scanf("%c",&a); /*2nd scanf*/
printf("%c\n",a );
return 0;
}

This will not work, because after the first scanf a newline is left
behind in the input stream, unconsumed.

I made this attempt to solve this problem

#include<stdio. h>
int main(void)
{
char a,b;
scanf("%c",&a);
printf("%c\n",a );
getchar(); /* putting getc(stdin) also worked*/
scanf("%c",&a);
printf("%c\n",a );
return 0;
}

Out of curiosity I tried this also,

#include<stdio. h>
int main(void)
{
char a,b;
scanf("%c",&a);
printf("%c\n",a );
scanf("\n%c",&a );
printf("%c\n",a );
return 0;
}

which gave me expected output.

But my question is (finally!) , why the following code doesn't work,

#include<stdio. h>
int main(void)
{
char a,b;
scanf("%c\n",&a ); /* 1st scanf */
printf("%c\n",a );
scanf("%c",&a); /* 2nd scanf */
printf("%c\n",a );
return 0;
}

My assumption was 1st scanf will consume the newline left in the input
stream.
Thanks for your time,
Yugi.

Sep 8 '06
14 13832
Ratan wrote:
>
There is NO flushall() function.

There is one function fflush(), which flushes out the i/o stream data.
Please do not top-post. Your answer belongs after, or intermixed
with, the snipped data to which you reply. See the links below in
my sig.

fflush DOES NOT deal with input streams. In fact, attempting to
apply it to one results in undefined behaviour. A useful function
to have around is:

int flushln(FILE *f) {
int ch;

while ((EOF != (ch = getc(f))) && ('\n' != ch)) continue;
return ch;
} /* flushln */

which will flush an input stream through the next '\n'.

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html

Sep 8 '06 #11
Richard Heathfield wrote:
Ratan said:
>There is NO flushall() function.

Correction: the C standard library does not provide one. Implementation
providers are free to provide a function by that name in a third-party
library if they choose, and at least one such provider does precisely that.
>There is one function fflush(), which flushes out the i/o stream data.

Indeed - and fflush(NULL) flushes out /all/ data currently pending on
streams open for output or update. This is guaranteed by the Standard.
However, it does *not* flush input streams. Standard C has no support
for flushing input streams.

I know you know this Richard, but I suspect Ratan does not.
--
Flash Gordon
Sep 8 '06 #12
Flash Gordon said:
Richard Heathfield wrote:
>>
[...] fflush(NULL) flushes out /all/ data currently pending on
streams open for output or update. This is guaranteed by the Standard.

However, it does *not* flush input streams. Standard C has no support
for flushing input streams.
Right. That's why I said it flushes *out* all data currently pending on
streams open for *output* or *update*.
I know you know this Richard, but I suspect Ratan does not.
That's why I corrected him.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 8 '06 #13
CBFalconer <cb********@yah oo.comwrites:
Ratan wrote:
>>
There is NO flushall() function.

There is one function fflush(), which flushes out the i/o stream data.

Please do not top-post. Your answer belongs after, or intermixed
with, the snipped data to which you reply. See the links below in
my sig.

fflush DOES NOT deal with input streams. In fact, attempting to
apply it to one results in undefined behaviour. A useful function
to have around is:

int flushln(FILE *f) {
int ch;

while ((EOF != (ch = getc(f))) && ('\n' != ch)) continue;
return ch;
} /* flushln */

which will flush an input stream through the next '\n'.
Yes, that's one possible meaning of "flushing" an input stream.

At least one system I know of defines fflush() for input streams:

<SYSTEM_SPECIFI C>
Flushing an input stream discards any buffered input and adjusts
the file pointer such that the next input operation accesses the
byte after the last one read.
</SYSTEM_SPECIFIC >

This is perfectly legitimate; one of the infinitely many possible
consequences of undefined behavior is to behave in a manner defined by
the implementation.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Sep 8 '06 #14
On Thu, 07 Sep 2006 23:15:56 -0700, main() wrote:

Robert Gamble wrote:
>main() wrote:
I know this is the problem that most newbies get into.

#include<stdio. h>
int main(void)
{
char a;
scanf("%c",&a); /*1st scanf */
printf("%c\n",a );
scanf("%c",&a); /*2nd scanf*/
printf("%c\n",a );
return 0;
}

This will not work, because after the first scanf a newline is left
behind in the input stream, unconsumed.

I made this attempt to solve this problem

#include<stdio. h>
int main(void)
{
char a,b;
scanf("%c",&a);
printf("%c\n",a );
getchar(); /* putting getc(stdin) also worked*/ scanf("%c",&a);
printf("%c\n",a );
return 0;
}

This will only work (the way you seem to want it to) if the second
character in the first input line is a newline. You introduced a new
variable here, b, did you mean to do something with it?
Out of curiosity I tried this also,

#include<stdio. h>
int main(void)
{
char a,b;
scanf("%c",&a);
printf("%c\n",a );
scanf("\n%c",&a );
printf("%c\n",a );
return 0;
}

which gave me expected output.

Any whitespace in the format string will match any amount of whitespace
in the input, including none. Your newline will match any number of
spaces, tabs, newlines, etc., until a non-whitespace character is
encountered.
But my question is (finally!) , why the following code doesn't work,

#include<stdio. h>
int main(void)
{
char a,b;
scanf("%c\n",&a ); /* 1st scanf */
printf("%c\n",a );
scanf("%c",&a); /* 2nd scanf */
printf("%c\n",a );
return 0;
}

My assumption was 1st scanf will consume the newline left in the
input
stream.

The first scanf call will store the first character into a and consume
of any immediately following whitespace (including newlines and any
whitespace that follows). You didn't specify what the input was that
you used or how the output differed from your expectations, so it's
difficult to help you understand what the "problem" is, feel free to
clarify.

Hi,

for the last code snippet
this is the output i got

y
z
y
z

when i entered y , it didn't print anything when i entered z, it
printed both y and z. What i expected is this,

y
y
z
z

Thanks for your time,
stdin is typically line-buffered, your input is seen by scanf one line at
a time. Scanf doesn't automatically return when it encounters an end of
line character, it returns when it finishes matching the format string or
when there is an input failure (end of file) or a matching failure
(something is encountered which doesn't match the format string). As
previously mentioned, any whitespace in the format string will match any
amount of whitespace in the input stream, your newline character will
match any amount of whitespace, the function will not return until it
encounters a non-whitespace character (or encounters end of file, etc.).
After reading the first character, 'y', the call to scanf is going to
continue reading from stdin, one character at a time, until it encounters
a non-whitespace character before returning. In the first line it assigns
the character 'y' to the variable a and then reads the newline which is a
whitespace character. Since scanf has not yet encountered a
non-whitespace character it is going to wait until the next line of input
is available and not return until it sees the 'z' on the second line. When
scanf encounters the 'z' it will see that it is not a whitespace
character, push it back onto the stream and return having finished
matching its format specifier. The second call to scanf will read the
character 'z' that the first call just pushed back and return immediately.

If you want to process input a line at a time your best bet is probably to
use fgets and sscanf.

Robert Gamble

Sep 9 '06 #15

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

Similar topics

4
7991
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' with scanf. ----------------------- double d;
39
100830
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 anything even a hint would be really helpful, I cant for the life of me see why the 2nd prog wont work... gets before scanf code:---------------------------------------------------------------------
12
9881
by: B Thomas | last post by:
Hi, I was reading O'Reilly's "Practical C programming" book and it warns against the use of scanf, suggesting to avoid using it completely . Instead it recomends to use using fgets and sscanf. However no explanation is offered other than that scanf handels end of lines very badly. I have exeperienced such problems when doing some numerical programming but never understood it. Things like some consequitive scanfs would not read in values...
5
3906
by: Eduardo Olivarez | last post by:
The following code does not work correctly on my machine. Either one of the scanf()'s alone work perfectly. However, when they are combined, the second scanf() call just reads what the first one received as imput, without taking any keyboard input and then the process terminates prematurely. I looked through the glibc documentation trying to figure out what was causing this to no avail, so I started messing around with the code. Strangely...
33
3198
by: Lalatendu Das | last post by:
Dear friends, I am getting a problem in the code while interacting with a nested Do-while loop It is skipping a scanf () function which it should not. I have written the whole code below. Please help me in finding why such thing is happening and what the remedy to it is. Kindly bear with my English. int main ()
6
26310
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 non-number, he/she will be asked to retry. /* start */ int n;
68
4681
by: stasgold | last post by:
Hello. I maybe reinvent the weel ... I'm trying to read positive integer number with the help of scanf, if the input value is not positive number but negaive one zero or char , i have to reread the input until I get the needed pos. number I wrote the code , but it doesn't work the way it should : if i put some char into input, the program goes infinite loop instead of promting me to enter a new value.
5
610
by: Jack | last post by:
Hi, can someone tell me what is wrong with this code. cout << "Enter the size of the array:"; cin >size; myVar = new char; myVar = 'a'; printf ("%c\n",myVar); puts ("Enter value for the first cell: ");
13
4402
by: FerrisUML | last post by:
Hello everyone! I new to C and am having the following problem. In the below program, the last scanf is being ignored and the program exits. Can anyone see anything that im doing wrong? Thanks in advance. #include <stdio.h> /* HOMEWORK: Assignment 1 Name: Dennis McQuilken
0
9944
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9797
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11154
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10863
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7977
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7136
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6005
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3241
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.