473,609 Members | 1,965 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

scanf() wierdness

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 enough, adding a call to getchar() in between the first scanf and
the second printf solves the problem. I have no idea why. Anyone kind
enough to enlighten me as to whats going on?

Non working code (minimized to isolate error):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define STRLEN 100

int main(void) {
int shift;
char *string;

string = (char *) malloc(sizeof(c har) * STRLEN);

printf("Input a number: ");
scanf("%d", &shift);
printf("Input a string: ");
scanf("%[^\n]100", string);

printf("%d\n", shift);
printf("%s\n", string);
}

Working code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define STRLEN 100

int main(void) {
int shift;
char *string;

string = (char *) malloc(sizeof(c har) * STRLEN);

printf("Input a number: ");
scanf("%d", &shift);
getchar();
printf("Input a string: ");
scanf("%[^\n]100", string);

printf("%d\n", shift);
printf("%s\n", string);
}

Output of non working code:

remus@phobos remus $ ./test
Input a number: 12
Input a string: 12

remus@phobos remus $

--
Eduardo Olivarez
<ed uardo oli varez at hot mail dot com>
Nov 14 '05 #1
5 3879
In article <vM************ *******@newssvr 31.news.prodigy .com>
Eduardo Olivarez wrote:

If I understand correctly, scanf pushes back at least one
character in the input stream. When you get the number from stdin, you
terminate input with newline character, which is pushed back in the
stdin. When you call scanf second time, it starts to read stdin and the
very first character is newline, so it stops reading.

--
Mad Wizard
Nov 14 '05 #2
On Fri, 23 Jan 2004, Eduardo Olivarez wrote:
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 enough, adding a call to getchar() in between the first scanf and
the second printf solves the problem. I have no idea why. Anyone kind
enough to enlighten me as to whats going on?
It is more accurate to say that "the followiung code does not do what I
expect on my machine." The problem is usually that it does the correct
thing but that we tend to misunderstand what the correct thing it.
Non working code (minimized to isolate error):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define STRLEN 100

int main(void) {
int shift;
char *string;

string = (char *) malloc(sizeof(c har) * STRLEN);
You shouldn't need the cast. If you failed to #include <stdlib.h> the
compiler will assume that malloc returns an int and that you want to cast
the int to a pointer to char. This is undefined behaviour. Just don't cast
the result of malloc. It should be returning a pointer to void and not
need the cast.

Additionally, sizeof(char) is always 1. Seems redundant to use it here.
printf("Input a number: ");
Add a fflush(stdout); after the printf. Search the newsgroup for
'fflush(stdout) ' and you'll probably find the explanation as to why.
scanf("%d", &shift);
If the user inputs "123\n" then scanf will read the "123", convert it to
123 and assign it to shift. The "\n" can remain on the stream.
printf("Input a string: ");
scanf("%[^\n]100", string);
This indicates to read 100 char until you reach a newline character. The
last scanf left the '\n' in the stream so this quits immediate and returns
0. You should check the return value of scanf and see if it was
successful. Your code below assumes it was. Don't assume when you can
check.
printf("%d\n", shift);
printf("%s\n", string);
return 0;
}
It is usually better to use fgets() to read in a line from the user then
use sscanf to scan the string. This will 'flush' the newline character
from the stdin stream.
Working code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define STRLEN 100

int main(void) {
int shift;
char *string;

string = (char *) malloc(sizeof(c har) * STRLEN);

printf("Input a number: ");
scanf("%d", &shift);
getchar();
This is a hack. Without understanding why you need this you should assume
the code still does not work. You can only assume it APPEARS to work. On
future runs it might fail.
printf("Input a string: ");
scanf("%[^\n]100", string);

printf("%d\n", shift);
printf("%s\n", string);
}

Output of non working code:

remus@phobos remus $ ./test
Input a number: 12
Input a string: 12

remus@phobos remus $

--
Eduardo Olivarez
<ed uardo oli varez at hot mail dot com>


--
Send e-mail to: darrell at cs dot toronto dot edu
Don't send e-mail to vi************@ whitehouse.gov
Nov 14 '05 #3
> > string = (char *) malloc(sizeof(c har) * STRLEN);

You shouldn't need the cast. If you failed to #include <stdlib.h> the
compiler will assume that malloc returns an int and that you want to cast
the int to a pointer to char. This is undefined behaviour. Just don't cast
the result of malloc. It should be returning a pointer to void and not
need the cast.

Additionally, sizeof(char) is always 1. Seems redundant to use it here.


Argh. I count 6 different active threads (posted to in the last
24 hours) where someone has "corrected" someone else's non-buggy
use of malloc(). Perhaps we need a new group, comp.lang.c.mal loc ?
Nov 14 '05 #4
Groovy hepcat Eduardo Olivarez was jivin' on Fri, 23 Jan 2004 08:17:31
GMT in comp.lang.c.
scanf() wierdness's a cool scene! Dig it!
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


READ THE FAQ!!! The FAQ exists for a reason: to answer questions
like this. Yet we still have to constantly tell people to read the
FAQ. This should be taken for granted, but no! You should also read
the newsgroup for some time. Your question is answered all the time.
You would know that if you had lurked here and read the FAQ, as you
should have done. It is very rude to post to a newsgroup without first
lurking for a while and reading its FAQ.
If I sound mean I'm sorry, but I'm tired of telling people to lurk
and read the FAQ. It should be the first thing you do when you enter a
newsgroup for the first time.
Lurk and ye shall see the FAQs.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technicall y correct" English; but since when was rock & roll "technicall y correct"?
Nov 14 '05 #5
Old Wolf <ol*****@inspir e.net.nz> wrote:
> string = (char *) malloc(sizeof(c har) * STRLEN);


You shouldn't need the cast. If you failed to #include <stdlib.h> the
compiler will assume that malloc returns an int and that you want to cast
the int to a pointer to char. This is undefined behaviour. Just don't cast
the result of malloc. It should be returning a pointer to void and not
need the cast.

Additionally, sizeof(char) is always 1. Seems redundant to use it here.


Argh. I count 6 different active threads (posted to in the last
24 hours) where someone has "corrected" someone else's non-buggy
use of malloc(). Perhaps we need a new group, comp.lang.c.mal loc ?


Oh, actually I think CLC considers such usage of malloc to be buggy.
There are arguments against such usage and as some say there are for.
But I personally do not understand those who say that you should cast
mallocs return value.
Why would you say someone should cast malloc?

--
Z (Zo**********@d aimlerchrysler. com)
"LISP is worth learning for the profound enlightenment experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days." -- Eric S. Raymond
Nov 14 '05 #6

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

Similar topics

0
1769
by: Matthew Alton | last post by:
The appended program freaks python 2.2 & 2.3 completely out. To reproduce the wierdness: i) copy the source to a file called consarn.py ii) $ python consarn.py; iii) the program is now doing a getch(); iv) hit a key; v) the program locks up, the interptreter is now munching on the CPU; vi) kill the interpreter from another shell; vii) scratch head and wonder why neither of the mutually exclusive clauses in the _io() member function...
13
1663
by: Tek Boy | last post by:
I've been experiencing some (reproducable) wierdness when I try to generate some very basic HTML using ASP. Check out the following (basic) ASP code: =========================================== <% Option Explicit Const STRING_1 = "/admin/UploadProgress2.asp" Const STRING_A = "AXFFile" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>
0
1339
by: amber | last post by:
Hello, I'm having some wierdness with a report I've created in VB.NET (with Crysal Reports). The report is called repCPDocSubmissionSummary.vb I created it a while ago, and have been using it successfully for months. Today I went in and did some edits, saved and closed it. Then, when I tried to build my project, I kept getting an error about ambiguous name (repCPDocSubmissionSummary). I looked in the folder, and saw there was a...
12
9839
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...
7
7652
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 scanf cannot fill any fields it returns EOF. I have run some tests on scanf and, so far, I've not found an EOF return. For example: If the programer formats scanf for an int or
14
13773
by: main() | last post by:
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);
3
9833
by: Tinku | last post by:
#include<stdio.h> main() { char line; scanf("%", line); printf("%s", line); } it will read and print the line but what is "%" in general we gives %s, %c .
9
1321
by: Bobby Edward | last post by:
Are there any add-ons to Visual Studio 2008 that will help me troubleshoot CSS wierdness? Like showing the padding/margin with difference colors, etc...? I'm trying to figure out some wierd floating and spacing issues? Discrepencies between FF and IE...
2
6544
by: subramanian100in | last post by:
Consider the following program named as x.c #include <stdlib.h> #include <stdio.h> int main(void) { unsigned int u; char str;
0
8145
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
8588
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...
0
8556
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8236
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,...
0
7030
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6068
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
5526
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
4037
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
1407
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.