473,396 Members | 1,968 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,396 software developers and data experts.

printf filestream ?

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
15 2473
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
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
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
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
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
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
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
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
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
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

"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

"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
>
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Shawn | last post by:
Hi. I'm using a FileStream (instead of just the path to the xml file) to load an XmlDocument. I'm doing this because I need to be able to prevent other processes to update the file I'm working on....
9
by: Tom | last post by:
I am working with the this object as oppose to the StreamReader object becuase I need to access a file (to find the contents) while an external application is updating the file. When I was...
5
by: Chris Fink | last post by:
How do I load a string into a FileStream without going to disk? For example, string abc = "This is a string"; How do I load abc into a FileStream? FileStream input = new FileStream(.....);
0
by: lh | last post by:
The following method only works when i give the ASP.net account full permissions on the directory. It doesn't work when i give the directory Modify, Read &Execute, List Folder Contents, Read, and...
9
by: ljlevend | last post by:
I have two questions related to FileStreams. 1. Is there any way to determine whether a file has the permissions that are required by a FileStream constructor? For example, given the following...
7
by: Nathan Sokalski | last post by:
I am having a problem saving an image with the same name it originally had. I have two similar versions of my code, one in which I close the FileStream used to open the original image before saving,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.