By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,200 Members | 1,612 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,200 IT Pros & Developers. It's quick & easy.

printf filestream ?

P: n/a
I just started learning C, and wrote this small program to play around
with the printf function in stdio.h. At the console, I am able to type
input at the first 2 getchar() calls, but when I call it again at big =
getchar(), I never get to type anything, it just reads ASCII 10 from
the stdin for some reason. Can someone explain why it is reading the
stdin stream at that point even though I am not typing, and how I would
get this to work.

CODE:
#include <stdio.h>
int main(){
int per1;
int per2;
int sumper;

printf("Type in two characters: \n");
per1 = getchar();
per2 = getchar();
sumper = per1 + per2;
printf("ASCII first number = %i\n",per1);
printf("ASCII second number = %i\n",per2);
printf("ASCII sum = %i\n",sumper);

int big;
printf("Type in a large number for scientific notation: \n");
big = getchar();
printf("Scientific Notation: %e\n", big);
printf("big = %i\n", big);

return 0;
}

RESULT:
Type in two characters:
50 /*I can type this in*/
ASCII first number = 53
ASCII second number = 48
ASCII sum = 101
Type in a large number for scientific notation:
Scientific Notation: 1.253353e-308 /*I don't get to type this in*/
big = 10

Dec 10 '06 #1
Share this Question
Share on Google+
15 Replies


P: n/a
Indeed, the getchar() gets one char only, so per1 = '5' and per2 = '0'

On Dec 11, 12:14 am, bryanv...@gmail.com wrote:
I just started learning C, and wrote this small program to play around
with the printf function in stdio.h. At the console, I am able to type
input at the first 2 getchar() calls, but when I call it again at big =
getchar(), I never get to type anything, it just reads ASCII 10 from
the stdin for some reason. Can someone explain why it is reading the
stdin stream at that point even though I am not typing, and how I would
get this to work.

CODE:
#include <stdio.h>
int main(){
int per1;
int per2;
int sumper;

printf("Type in two characters: \n");
per1 = getchar();
per2 = getchar();
sumper = per1 + per2;
printf("ASCII first number = %i\n",per1);
printf("ASCII second number = %i\n",per2);
printf("ASCII sum = %i\n",sumper);

int big;
printf("Type in a large number for scientific notation: \n");
big = getchar();
printf("Scientific Notation: %e\n", big);
printf("big = %i\n", big);

return 0;

}RESULT:
Type in two characters:
50 /*I can type this in*/
ASCII first number = 53
ASCII second number = 48
ASCII sum = 101
Type in a large number for scientific notation:
Scientific Notation: 1.253353e-308 /*I don't get to type this in*/
big = 10
Dec 10 '06 #2

P: n/a
br*******@gmail.com writes:
I just started learning C, and wrote this small program to play around
with the printf function in stdio.h. At the console, I am able to type
input at the first 2 getchar() calls, but when I call it again at big =
getchar(), I never get to type anything, it just reads ASCII 10 from
the stdin for some reason. Can someone explain why it is reading the
stdin stream at that point even though I am not typing, and how I would
get this to work.

CODE:
#include <stdio.h>
int main(){
Better: "int main(void)".
int per1;
int per2;
int sumper;

printf("Type in two characters: \n");
per1 = getchar();
per2 = getchar();
You probably typed three characters in response to the prompt, the
first two characters plus a newline. (A newline, '\n', happens to be
ASCII 10 on most systems.)
sumper = per1 + per2;
printf("ASCII first number = %i\n",per1);
printf("ASCII second number = %i\n",per2);
printf("ASCII sum = %i\n",sumper);

int big;
printf("Type in a large number for scientific notation: \n");
big = getchar();
This reads the newline you typed above.
printf("Scientific Notation: %e\n", big);
"big" is of type int (and it holds a single character value). The
"%e" format expects an argument of type double. You're lying to
printf(). The result is undefined behavior.
printf("big = %i\n", big);
And here you show the decimal value of the newline character.
return 0;
}
You want to read a floating-point value from stdin. getchar() just
reads single characters.

You can either use scanf() to read a floating-point value (see the
documentation for scanf() -- but beware, there are a lot of pitfalls),
or you can read a string and use some function to convert it.

A good way to do text input is to read a line at a time using fgets()
and then process the result. fgets() can have problems with very long
lines, but you probably don't need to worry about that just yet.

You'll also eventually want to worry about EOF.

Feel free to post your second attempt; we'll be glad to tear that
apart too. 8-)}

--
Keith Thompson (The_Other_Keith) 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.
Dec 10 '06 #3

P: n/a
br*******@gmail.com wrote:
I just started learning C, and wrote this small program to play around
with the printf function in stdio.h. At the console, I am able to type
input at the first 2 getchar() calls, but when I call it again at big =
getchar(), I never get to type anything, it just reads ASCII 10 from
the stdin for some reason. Can someone explain why it is reading the
stdin stream at that point even though I am not typing, and how I would
get this to work.

CODE:
#include <stdio.h>
int main(){
int main(void)
int per1;
int per2;
int sumper;

printf("Type in two characters: \n");
per1 = getchar();
per2 = getchar();
Check for EOF.
sumper = per1 + per2;
printf("ASCII first number = %i\n",per1);
printf("ASCII second number = %i\n",per2);
printf("ASCII sum = %i\n",sumper);
Don't assume ASCII. And they're not numbers. They're encoded values for
characters.
int big;
C90 doesn't support mixed declarations. Place all declarations at the
beginning of a block.
printf("Type in a large number for scientific notation: \n");
big = getchar();
printf("Scientific Notation: %e\n", big);
How do expect this? Have you not seen the documentation for getchar()?
getchar() reads only one character from the stdin stream. A large
number will consist of several characters, unless for you, 9 is a large
number. getchar() will only retrieve the first of the characters making
up this number. When you type in a number, it's processed by the
program as a sequence of characters, and then converted to an integer,
if neccessary. To read in a large number do:

long large_num; /* place this at the beginning of the code block */
puts("Enter a large number:");
scanf("%ld", &large_num);

scanf() has several tricky issues, but at this point you needn't worry
about them.

Dec 10 '06 #4

P: n/a
Thanks for the input. I didn't realize that the getchar() at the sci.
notation part would read my pressing 'Enter' after typing 50 above.
Since the getchar() code comes after I press 'Enter', I thought that
new line feed would just not be read and not handled by my code. I
guess it remembers each keystroke? I'll get the hang of it with more
practice I suppose. As for the scientific notation, I wasn't really
trying to pass it a real number, I was just messing with some of the
different formating options of printf. Haven't got to mess around with
float points yet, just single digit integers.

Dec 10 '06 #5

P: n/a
On 10 Dec 2006 08:14:23 -0800, br*******@gmail.com wrote:
>I just started learning C, and wrote this small program to play around
with the printf function in stdio.h. At the console, I am able to type
input at the first 2 getchar() calls, but when I call it again at big =
Not quite true. At the first call to getchar, you typed three
keystrokes, two input characters plus the enter key. (To demonstrate
this for yourself, re-run the program and at the first call to getchar
type one character plus enter.) The first keystroke was acquired by
getchar and stored in per1. The following two keystrokes remained in
your system's input buffer. At the second call, the first of these
remaining characters was acquired by getchar and stored in per2. The
enter keystroke is still in the buffer.
>getchar(), I never get to type anything, it just reads ASCII 10 from
the stdin for some reason. Can someone explain why it is reading the
The reason is getchar does not read from your keyboard but from your
system's input buffer. ASCII 10 is the \n character which is what
your system translates the enter into.
>stdin stream at that point even though I am not typing, and how I would
get this to work.
Since your system will not pass any data to getchar until you press
enter, recognize that there is no way for a single keystroke (other
than enter) to satisfy the getchar. The other side of the coin is you
have no idea how many keystrokes were entered before the enter key was
pressed.

One approach would be to use fgets to read in the entire set of input
characters including the enter and then use only the first. This is
not entirely bullet proof because user could enter more characters
than the buffer you pass to fgets.

A more robust approach is after each call to getchar to execute
additional code that will drain the input buffer of any extraneous
characters (of which there must be at least one). Something similar
to this function which you could call after each call to getchar:
void drain(void){
int x;
while ((x = getchar()) != '\n' && x != EOF)
;
}
>
CODE:
#include <stdio.h>
int main(){
int per1;
int per2;
int sumper;

printf("Type in two characters: \n");
per1 = getchar();
per2 = getchar();
sumper = per1 + per2;
printf("ASCII first number = %i\n",per1);
printf("ASCII second number = %i\n",per2);
printf("ASCII sum = %i\n",sumper);

int big;
printf("Type in a large number for scientific notation: \n");
big = getchar();
printf("Scientific Notation: %e\n", big);
This invokes undefined behavior. The %e promises printf that the
corresponding argument will be a double. big is an int.

Even if you change big to a double, the code will not do what you
intend. getchar will only store the value of one character in big,
not the numeric value corresponding to the number you enter. If you
enter 12.34, getchar will extract the '1', which is 0x31 on an ASCII
system. This will result in big receiving the value 49.0. The
remaining four characters plus enter are still in the buffer waiting
patiently for you to use them.
> printf("big = %i\n", big);

return 0;
}

RESULT:
Type in two characters:
50 /*I can type this in*/
ASCII first number = 53
ASCII second number = 48
ASCII sum = 101
Type in a large number for scientific notation:
Scientific Notation: 1.253353e-308 /*I don't get to type this in*/
Actually you did. You just typed in something other than what you
intended at a time earlier than you expected.
>big = 10

Remove del for email
Dec 10 '06 #6

P: n/a
That cleared everything up Barry, excellent! For my small scope, I was
able to place one more getchar() before I wanted to enter another
character, this "handled" the new line key press from before and left
the console wanting me to type in a character.
I am learning from "Sams Teach Yourself C in 24 Hours", which did not
explain (at least in chapter 5) that stdin was actually reading from a
buffer. The way it reads it seems like it is reading from the keyboard
in real time.

Dec 10 '06 #7

P: n/a
Bryan wrote:
Thanks for the input. I didn't realize that the getchar() at the sci.
notation part would read my pressing 'Enter' after typing 50 above.
Since the getchar() code comes after I press 'Enter', I thought that
new line feed would just not be read and not handled by my code. I
guess it remembers each keystroke? I'll get the hang of it with more
practice I suppose. As for the scientific notation, I wasn't really
trying to pass it a real number, I was just messing with some of the
different formating options of printf. Haven't got to mess around with
float points yet, just single digit integers.
Please quote the post you're replying to, since on Usenet, access to
previous articles might not always be easy.
>From your post it's obvious you're having difficulty in understanding
the fundamentals of the computer.

Under most operating systems, input from the keyboard is line buffered.
That means that the OS will store the characters you enter via the
keyboard until you press Enter or Return, i.e. enter a complete line.
Then and only then will the OS deliver the whole line to your
application. In this case, the line is delivered to the C standard
library, or more precisely, the part of it that handles I/O. This input
is stored in an internal buffer. getchar() then reads from this buffer
and since it's meant to return a single character, it will read the
first value of this buffer and return it, leaving the rest of the line
still waiting in the buffer. Subsequent calls to input functions will
read this line before blocking for fresh input from the actual hardware
device, i.e. the keyboard.

The whole process, when you look at the details is rather complicated
symbiosis of your application, it's library code and the operating
systems.

Also not all operating systems behave in the manner described above.
What I described is just typical for keyboard input. There're special
OS calls to change this behaviour, but all that's advanced and totally
off-topic to this group.

PS. If you don't understand words like 'operating system', 'I/O' etc.,
you might want to read a basic book on computers before starting to
program. Programming generally requires some amount of basic knowledge
of computers and using them, i.e. meaning of various common terms etc.

Dec 10 '06 #8

P: n/a
br*******@gmail.com said:

<snip>
>
printf("Type in two characters: \n");
per1 = getchar();
per2 = getchar();
I bet you actually hit three keys, not two - the third of which is your
ENTER key.

The first is read into per1, and the second into per2. The third, however -
the newline character that is generated on stdin when you hit ENTER - is
just sat there, waiting, waiting...
sumper = per1 + per2;
printf("ASCII first number = %i\n",per1);
printf("ASCII second number = %i\n",per2);
printf("ASCII sum = %i\n",sumper);

int big;
printf("Type in a large number for scientific notation: \n");
big = getchar();
....until you read that newline character, right here.

stdin is line-buffered by default, so it stores up input until either it
fills the buffer or it encounters a newline character in the buffer.

In your case, it was the latter. Your stdin consists of '5', '0', and '\n'.
The last of these characters is read by your third getchar call.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 10 '06 #9

P: n/a
Thank you. I'm just proving the stereotype here, but I actually have
written several client side GUI applications in visual basic and never
had to know anything at this depth. I started off programming in
visual basic as a hobby. I recently started watching online video
lectures from the MIT computer science department, and quickly realized
that visual basic + visual studio 2005 = not best place to start
programming for exactly this reason. It's easy to build simple windows
forms apps quickly in VS, but I want to be able to write code that
interacts with the computer at the lowest levels and is portable. So I
chose C as a place to start. Any advice on building a strong
foundation through self teaching would be appreciated.

santosh wrote:
Bryan wrote:
Thanks for the input. I didn't realize that the getchar() at the sci.
notation part would read my pressing 'Enter' after typing 50 above.
Since the getchar() code comes after I press 'Enter', I thought that
new line feed would just not be read and not handled by my code. I
guess it remembers each keystroke? I'll get the hang of it with more
practice I suppose. As for the scientific notation, I wasn't really
trying to pass it a real number, I was just messing with some of the
different formating options of printf. Haven't got to mess around with
float points yet, just single digit integers.

Please quote the post you're replying to, since on Usenet, access to
previous articles might not always be easy.
From your post it's obvious you're having difficulty in understanding
the fundamentals of the computer.

Under most operating systems, input from the keyboard is line buffered.
That means that the OS will store the characters you enter via the
keyboard until you press Enter or Return, i.e. enter a complete line.
Then and only then will the OS deliver the whole line to your
application. In this case, the line is delivered to the C standard
library, or more precisely, the part of it that handles I/O. This input
is stored in an internal buffer. getchar() then reads from this buffer
and since it's meant to return a single character, it will read the
first value of this buffer and return it, leaving the rest of the line
still waiting in the buffer. Subsequent calls to input functions will
read this line before blocking for fresh input from the actual hardware
device, i.e. the keyboard.

The whole process, when you look at the details is rather complicated
symbiosis of your application, it's library code and the operating
systems.

Also not all operating systems behave in the manner described above.
What I described is just typical for keyboard input. There're special
OS calls to change this behaviour, but all that's advanced and totally
off-topic to this group.

PS. If you don't understand words like 'operating system', 'I/O' etc.,
you might want to read a basic book on computers before starting to
program. Programming generally requires some amount of basic knowledge
of computers and using them, i.e. meaning of various common terms etc.
Dec 10 '06 #10

P: n/a
Bryan wrote:
>
Thank you. I'm just proving the stereotype here, but I actually
have written several client side GUI applications in visual basic
and never had to know anything at this depth. I started off
programming in visual basic as a hobby. I recently started
watching online video lectures from the MIT computer science
department, and quickly realized that visual basic + visual studio
2005 = not best place to start programming for exactly this reason.
It's easy to build simple windows forms apps quickly in VS, but I
want to be able to write code that interacts with the computer at
the lowest levels and is portable. So I chose C as a place to
start. Any advice on building a strong foundation through self
teaching would be appreciated.
Besides learning to quote adequately, you need to learn NOT to
top-post. Your answer belongs after, or intermixed with, the
material you quote, after snipping anything irrelevant to your
answer. See the links below.

--
Some informative links:
<news:news.announce.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>
<http://cfaj.freeshell.org/google/>
Dec 10 '06 #11

P: n/a

"Bryan wrote:
"
Thank you. I'm just proving the stereotype here, but I actually have
written several client side GUI applications in visual basic and never
had to know anything at this depth. I started off programming in
visual basic as a hobby. I recently started watching online video
lectures from the MIT computer science department, and quickly realized
that visual basic + visual studio 2005 = not best place to start
programming for exactly this reason. It's easy to build simple windows
forms apps quickly in VS, but I want to be able to write code that
interacts with the computer at the lowest levels and is portable. So I
chose C as a place to start. Any advice on building a strong
foundation through self teaching would be appreciated.
VB is bad, for it is MS's private language.

C is not a good place to start your programming. See esr's How To
Become a Hacker to learn more.(Python or Java may be better.)

VC is bad too, it omits some very useful warnings and its debugger
sucks. What's more, it is very expensive. Try gcc+gdb instead.

Dec 11 '06 #12

P: n/a

"Bryan wrote:
"
Thank you. I'm just proving the stereotype here, but I actually have
written several client side GUI applications in visual basic and never
had to know anything at this depth. I started off programming in
visual basic as a hobby. I recently started watching online video
lectures from the MIT computer science department, and quickly realized
that visual basic + visual studio 2005 = not best place to start
programming for exactly this reason. It's easy to build simple windows
forms apps quickly in VS, but I want to be able to write code that
interacts with the computer at the lowest levels and is portable. So I
chose C as a place to start. Any advice on building a strong
foundation through self teaching would be appreciated.
VB is bad, for it is MS's private language.

C is not a good place to start your programming. See esr's How To
Become a Hacker to learn more.(Python or Java may be better.)

VC is bad too, it omits some very useful warnings and its debugger
sucks. What's more, it is very expensive. Try gcc+gdb instead.

Dec 11 '06 #13

P: n/a
>
A more robust approach is after each call to getchar to execute
additional code that will drain the input buffer of any extraneous
characters (of which there must be at least one). Something similar
to this function which you could call after each call to getchar:
void drain(void){
int x;
while ((x = getchar()) != '\n' && x != EOF)
;
}
How about fflush(stdin); ? ;-)

Dec 11 '06 #14

P: n/a
sa*****@yahoo.co.in wrote:

A more robust approach is after each call to getchar to execute
additional code that will drain the input buffer of any extraneous
characters (of which there must be at least one). Something similar
to this function which you could call after each call to getchar:
void drain(void){
int x;
while ((x = getchar()) != '\n' && x != EOF)
;
}

How about fflush(stdin); ? ;-)
I hope you know that that's undefined as per the standard.

Dec 11 '06 #15

P: n/a
On 11 Dec 2006 05:41:55 -0800, sa*****@yahoo.co.in wrote:
>
>>
A more robust approach is after each call to getchar to execute
additional code that will drain the input buffer of any extraneous
characters (of which there must be at least one). Something similar
to this function which you could call after each call to getchar:
void drain(void){
int x;
while ((x = getchar()) != '\n' && x != EOF)
;
}

How about fflush(stdin); ? ;-)
fflush is only defined for output files.
Remove del for email
Dec 12 '06 #16

This discussion thread is closed

Replies have been disabled for this discussion.