473,569 Members | 2,782 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A problem with reading in a character.

Hello,

I'm having trouble reading in a character. Here is a snippet of code:

int num;
char character;

printf("Enter a number: ");
scanf("%d", &num);
printf("You entered %d.\n", num);

printf("Enter a character: ");
scanf("%c", &character);
printf("You entered %c.\n", character);

When I run this, I get:

Enter a number: 3
You entered 3.
Enter a character: You entered
..

I'm not sure why I'm unable to enter in a character before the last
printf is executed. I'm also tried this with getchar(), with the same
result.

Any help is appreciated.
Nov 13 '05 #1
6 6206

"Gus Tabares" <gu********@ver izon.net> schrieb im Newsbeitrag
news:c4******** *************** ***@posting.goo gle.com...
Hello,

I'm having trouble reading in a character. Here is a snippet of code:

int num;
char character;

printf("Enter a number: ");
scanf("%d", &num);
printf("You entered %d.\n", num);

printf("Enter a character: ");
scanf("%c", &character);
printf("You entered %c.\n", character);

When I run this, I get:

Enter a number: 3
You entered 3.
Enter a character: You entered
.

^^^^

Hint:
You have no trouble reading a character, you just read the wrong character
:)
Why is the last dot a line below the prompt?
Can it be, that the printed character is '\n' ?
What exactly was your first input, and where did your first scanf() stop
consuming input?
HTH
Robert
Nov 13 '05 #2
gu********@veri zon.net (Gus Tabares) writes:
Hello,

I'm having trouble reading in a character. Here is a snippet of code:

int num;
char character;

printf("Enter a number: ");
scanf("%d", &num);
printf("You entered %d.\n", num);

printf("Enter a character: ");
scanf("%c", &character);
printf("You entered %c.\n", character);

When I run this, I get:

Enter a number: 3
You entered 3.
Enter a character: You entered
.


See the C FAQ at <http://www.eskimo.com/~scs/C-faq/top.html>,
particularly question 12.18. I recommend browsing around the rest of
the FAQ while you're there.

(BTW, 12.18 refers to the gets() function without condemning it, but
see also 12.23.)

--
Keith Thompson (The_Other_Keit h) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #3
gu********@veri zon.net (Gus Tabares) wrote in message news:<c4******* *************** ****@posting.go ogle.com>...
[snip]
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered %d.\n", num);

printf("Enter a character: ");
scanf("%c", &character);
printf("You entered %c.\n", character);

When I run this, I get:

Enter a number: 3 Ok what you are really doing here is entering 2 characters, not one.
These are '3' and '\n'. Whenever scanf gets a '\n' it will stop
scanning its input. However it leaves '\n' inside the input queue.
So when it started reading from the input queue it read 3 ... then
said .. ok this is valid... lets see what the next character is ...
its '\n'... That means that I must stop scanning. The '3' which it
read was duly converted to an integer and stored in num.
You entered 3.
Now it prints out that num.

Next line is the crucial one. Remember that it removed '3' from the
input but '\n' still remains.

So when the second scanf looks for an input it finds '\n' and stops
immediatly and the '\n' is read into character.

That is why when you print out the next line, there is a newline
between the "You entered" and the "." .
Enter a character: You entered
.

Nov 13 '05 #4

"Anupam" <an************ **@persistent.c o.in> wrote in message
news:aa******** *************** **@posting.goog le.com...
gu********@veri zon.net (Gus Tabares) wrote in message news:<c4******* *************** ****@posting.go ogle.com>... [snip]
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered %d.\n", num);

printf("Enter a character: ");
scanf("%c", &character);
printf("You entered %c.\n", character);

When I run this, I get:

Enter a number: 3

Ok what you are really doing here is entering 2 characters, not one.
These are '3' and '\n'. Whenever scanf gets a '\n' it will stop
scanning its input. However it leaves '\n' inside the input queue.
So when it started reading from the input queue it read 3 ... then
said .. ok this is valid... lets see what the next character is ...
its '\n'... That means that I must stop scanning. The '3' which it
read was duly converted to an integer and stored in num.
You entered 3.


Now it prints out that num.

Next line is the crucial one. Remember that it removed '3' from the
input but '\n' still remains.

So when the second scanf looks for an input it finds '\n' and stops
immediatly and the '\n' is read into character.

That is why when you print out the next line, there is a newline
between the "You entered" and the "." .
Enter a character: You entered
.


I am aware that there are many solutions to this (one I can think of is
including a getch() in between the 2 scanfs). However, I am not satisfied
with this method and the extra getch() expects some comments to make the
code more readable.

My question is:

Is there any library function that can flush the standard input at a user
discretion. I read somewhere that fflush(stdin) is an undefined behavior. am
I correct? what is the best solution for this?

Thanks and Regards,
Praveen Kumar
Nov 13 '05 #5
"sahukar praveen" <sa************ @yahoo.co.in> wrote in message news:<3f******@ usenet01.boi.hp .com>...

[snip]
I am aware that there are many solutions to this (one I can think of is
including a getch() in between the 2 scanfs). However, I am not satisfied
with this method and the extra getch() expects some comments to make the
code more readable.
The best way would be to write your own function which keeps reading
characters in a loop using _getchar()_ until you get an EOF. However
be sure to check that it was indeed the end of the stream using feof()
.... it might have been a read error. You would be ill-advised to use
getch(). It is not standardised.

My question is:

Is there any library function that can flush the standard input at a user
discretion. I read somewhere that fflush(stdin) is an undefined behavior. am
I correct? what is the best solution for this?
Correct, there is no way as per the standard ( as per my knowledge
of the standard, which may not be perfect ) to remove the characters
waiting at an input queue without reading them and without invoking
UB. The only real solution is the one you mention which is to eat up
the intervening characters by reading them without using them . fflush
is not defined on input streams.

Thanks and Regards,
Praveen Kumar

Nov 13 '05 #6
sahukar praveen wrote:
.... snip ...
I am aware that there are many solutions to this (one I can think
of is including a getch() in between the 2 scanfs). However, I am
not satisfied with this method and the extra getch() expects some
comments to make the code more readable.

My question is:

Is there any library function that can flush the standard input
at a user discretion. I read somewhere that fflush(stdin) is an
undefined behavior. am I correct? what is the best solution for
this?


scanf is not generally suitable for interactive input. You have
two basic choices. Input a complete line and parse it with
sscanf, or use getc and ungetc and your own conversion routines
from stream input. The first has the problem of reading the
complete line, of unknown length, and fgets is not completely
suitable. The second can be highly efficient, but requires you
write all the conversion routines correctly. My ggets can help
with the first, as I pointed out elsewhere.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 13 '05 #7

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

Similar topics

4
3129
by: Matt Chaplain | last post by:
Hi there. I'm writing a program that uses the Telnet protocol over TCP/IP sockets. Of course, that has no bearing here, so I'll rephrase that in Standard C++ :) In essense, I'm trying to manipulate a data stream by using a custom streambuf, so that I can access this as "just another iostream". Alas, this data stream has a couple of...
2
3018
by: Tom | last post by:
OK I'm trying to go to the end of a file and delete the contents upwards until I meet a certain character. How can I do this? (NOTE: I'm using text files)
1
2008
by: Need Helps | last post by:
Hello. I'm writing an application that writes to a file a month, day, year, number of comments, then some strings for the comments. So the format for each record would look like: mdyn"comment~""comment~"\n Now, I wrote some code to read these records, and it works perfectly for every date I've tried it on, except when the day is 26. I tried...
2
1267
by: SteMc | last post by:
today I tackled, for the first time, opening and reading from a text file. Following the example on the MSDN and declared a variable, strline as a string and objstreamreader as a streamreader. Basically I read in a line of a text file - this works fine. I then read in another line. This works fine However, the third time round I read...
3
7901
by: Mike | last post by:
I seem to be having a problem with the following piece of (simple) code: """ #include <iostream> using namespace std; int main() { char ch;
2
1825
by: shblack | last post by:
I need help with a program I am writing for school. The program has to do the following: /* 1. Character string must be a minimium of 15 charactors. 2. If not 15 characters long it must give error and send you back to orginal question. 3. After entering 15 characters it must count the CAPTIAL letters and tell you how many there are. ...
10
3331
by: hsmit.home | last post by:
Hi everyone, I'm having some difficulty with the following piece of code. I have stripped it to it's bare minimum to demonstrate the problem at hand. Compiler: MS Visual C++ 2005 Express Edition (similar problem arises with 2008) Runtime Library: All multi-threaded variants have been seen to fail |
9
1867
by: Amkcoder | last post by:
I am trying to read a file a character at a time, I want to read in the new line character. I am printing out each character to the screen. For some reason it will not print out the new line. I want to do this so the line will break on the console while reading it in a character at a time. I am using fgetc on a file opened for reading in...
7
1635
by: tshad | last post by:
I have a program in 2005 that is reading a text file removing text and then writing it back out again. It removes lines that start with PRINT. This program has worked fine for months. Now all of a sudden, it is reading a straight text file and adding a null after each character it reads in. Why is that? The original file doesn't have...
0
7697
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...
0
8120
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7672
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...
0
6283
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5219
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...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1212
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
937
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...

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.