473,804 Members | 3,163 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proper use of scanf


Hello,

I am aware that a lot of people are wary of using scanf,
because doing it improperly can be dangerous. I have
tried to find a good tutorial on all the ins and outs
of scanf() but been unsuccessful.

Is there a well-respected (by the c.l.c crowd) book
or tutorial that really covers scanf in detail?
Nov 14 '05 #1
17 3505
Lefty Bigfoot wrote:

Hello,

I am aware that a lot of people are wary of using scanf,
because doing it improperly can be dangerous. I have
tried to find a good tutorial on all the ins and outs
of scanf() but been unsuccessful.

Is there a well-respected (by the c.l.c crowd) book
or tutorial that really covers scanf in detail?


I don't know of one.
Here's two examples of one way to use scanf safely.
If you enter more than LENGTH characters,
the extra ones will be automatically discarded.
If you have questions, I can try to explain.
The whole topic of scanf is somewhat lengthy.

/* BEGIN anystring.c */

#include <stdio.h>

#define LENGTH 20
#define str(x) #x
#define xstr(x) str(x)

int main(void)
{
char string[LENGTH + 1];
int rc;

printf("Enter any string or enter an empty string to quit: ");
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", string);
if (!feof(stdin)) {
getchar();
}
while (rc == 1) {
printf("Your string was %s\n", string);
printf("scanf() returned %d\n", rc);
printf("Enter any string or enter an empty string to quit: ");
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", string);
if (!feof(stdin)) {
getchar();
}
}
printf("scanf() returned %d\n", rc);
return 0;
}

/* END anystring.c */
/* BEGIN grade.c */

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

#define LENGTH 3
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
int rc;
char array[LENGTH + 1];
long number;
const char letter[4] = "DCBA";

fputs("Enter the Numeric grade: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getchar();
}
while (rc == 1) {
number = strtol(array, NULL, 10);
if (number > 60) {
if (number > 99) {
number = 99;
}
array[0] = letter[(number - 60) / 10];
switch (number % 10) {
case 0:
case 1:
array[1] = '-';
array[2] = '\0';
break;
case 8:
case 9:
array[1] = '+';
array[2] = '\0';
break;
default:
array[1] = '\0';
break;
}
} else {
array[0] = 'F';
array[1] = '\0';
}
printf("The Letter grade is: %s\n", array);
fputs("Enter the Numeric grade: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getchar();
}
}
return 0;
}

/* END grade.c */
--
pete
Nov 14 '05 #2

Le 19/06/2005 00:54, dans no************* *************@n ews.verizon.net,
«*Lefty Bigfoot*» <no****@awol.in fo> a écrit*:

Hello,

I am aware that a lot of people are wary of using scanf,
because doing it improperly can be dangerous. I have
tried to find a good tutorial on all the ins and outs
of scanf() but been unsuccessful.

Is there a well-respected (by the c.l.c crowd) book
or tutorial that really covers scanf in detail?


Yes, the ISO 9899-1999 Standard, section 7.19.6.4.
I can swear it's well respected here :-)

There is also the POSIX standard, at
http://www.opengroup.org/onlinepubs/000095399/
certainly well respected too.

If you want a tutorial, maybe the K&R C book will help you.

If you have UNIX or Linux, try "man scanf"

Nov 14 '05 #3
Lefty Bigfoot wrote:

I am aware that a lot of people are wary of using scanf,
because doing it improperly can be dangerous. I have
tried to find a good tutorial on all the ins and outs
of scanf() but been unsuccessful.

Is there a well-respected (by the c.l.c crowd) book
or tutorial that really covers scanf in detail?


Take a look at the links in my sig. Especially the one marked
C-library, and then the C99 one.

--
Some useful references about C:
<http://www.ungerhu.com/jxh/clc.welcome.txt >
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)
<http://www.dinkumware. com/refxc.html> (C-library}
<http://gcc.gnu.org/onlinedocs/> (GNU docs)

Nov 14 '05 #4
There seems to be some problem with the way I am using scanf() in my
code. Could please help me out?

/*Sample Program*/

#include<stdio. h>

int main()
{
double D;

scanf("%g", &D);
printf("%g", D);

return 0;
}

/*During Execution*/
1232 /*Input*/

5.68642e-315/*Output*/

/*End*/

If it helps, I am using the gcc compiler(ver 3.4.3) that I got with
DJGPP and I am using it on Win98.

Nov 14 '05 #5
Hello,

I just found a post from a person having the same problem. How cool is
that! The one mistake I found out is that '%g' in the scanf should be
'%lg'. Anyother nit picking will be welcomed.

Nov 14 '05 #6
Vivek wrote:
There seems to be some problem with the way I am using scanf() in my
code. Could please help me out?

/*Sample Program*/
#include<stdio. h>
int main()
{
double D;
scanf("%g", &D);
printf("%g", D);
return 0;
}

/*During Execution*/
1232 /*Input*/
5.68642e-315/*Output*/

#include<stdio. h>

int main(void)
{
double D;
char input[] = "1234";

printf("Using the OP's incorrect specifier for\n"
"reading the string \"%s\" as a double:", input);
sscanf(input, "%g", &D);
printf("%g\n", D);

printf("Using the correct specifier for\n"
"reading the string \"%s\" as a double:", input);
sscanf(input, "%lg", &D);
printf("%g\n", D);

return 0;
}

[output]
Using the OP's incorrect specifier for
reading the string "1234" as a double:2.88675e-13
Using the correct specifier for
reading the string "1234" as a double:1234
If it helps, I am using the gcc compiler(ver 3.4.3) that I got with
DJGPP and I am using it on Win98.


If you had turned on the warnings during compilation, gcc would have
told you the specifier was wrong. Not all compilers are so obliging.
Keep those warning levels up, and don't ignore the diagnostics.

Nov 14 '05 #7
Vivek wrote:
There seems to be some problem with the way I am using scanf() in my
code. Could please help me out?
[...]
double D;
scanf("%g", &D);
[...]

If it helps, I am using the gcc compiler(ver 3.4.3) that I got with
DJGPP and I am using it on Win98.


The compiler you're using happens to be able to
catch this error for you, if you ask it nicely. Use
the command-line flags "-Wall -W"; for code that's
intended to be portable use "-Wall -W -ansi -pedantic".
(There are alternatives to "-ansi"; see the info pages.)

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 14 '05 #8
Eric Sosman wrote:
Vivek wrote:
There seems to be some problem with the way I am using scanf()
in my code. Could please help me out?
[...]
double D;
scanf("%g", &D);
[...]

If it helps, I am using the gcc compiler(ver 3.4.3) that I got
with DJGPP and I am using it on Win98.


The compiler you're using happens to be able to
catch this error for you, if you ask it nicely. Use
the command-line flags "-Wall -W"; for code that's
intended to be portable use "-Wall -W -ansi -pedantic".
(There are alternatives to "-ansi"; see the info pages.)


This is one more of a long list of anomalies in scanf, and adds to
the list of reasons not to use it. Unfortunately the C library
lacks good routines to input from streams (rather than buffers). I
have written and published some suitable routines in the past.

To the OP - look up the modifier l (small ell) in the scanf
documentation. Read it with great care. Then don't use it, get
complete lines and work on those.

--
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
Nov 14 '05 #9
On Sun, 19 Jun 2005 02:08:52 +0200, Jean-Claude Arbaut
<je************ ****@laposte.ne t> wrote in comp.lang.c:

Le 19/06/2005 00:54, dans no************* *************@n ews.verizon.net,
«*Lefty Bigfoot*» <no****@awol.in fo> a écrit*:

Hello,

I am aware that a lot of people are wary of using scanf,
because doing it improperly can be dangerous. I have
tried to find a good tutorial on all the ins and outs
of scanf() but been unsuccessful.

Is there a well-respected (by the c.l.c crowd) book
or tutorial that really covers scanf in detail?
Yes, the ISO 9899-1999 Standard, section 7.19.6.4.
I can swear it's well respected here :-)


That's actually not a reference to how to use the function safely, nor
even a recommendation that it should be used.

See 7.19.7.7, which describes the gets() function, and includes not so
much as a hint of a warning about buffer overflows.
There is also the POSIX standard, at
http://www.opengroup.org/onlinepubs/000095399/
certainly well respected too.

If you want a tutorial, maybe the K&R C book will help you.

If you have UNIX or Linux, try "man scanf"


The general consensus here, which I agree with, is that the *scanf()
functions are best avoided by all except extreme experts on their use.
If non-experts avoid them, the will never become extreme experts,
making the point moot.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #10

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

Similar topics

12
9876
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...
14
2749
by: Peter Mount | last post by:
Hello I'm having trouble with " scanf("%c", &answer);" on line 20 below. When I run the program in cygwin on Windows 98SE it skips that line completely and ends the program. Does scanf have problems with "%c" or is it the operating system I'm using? 1 #include <stdio.h> 2 3 int main()
7
7665
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
4
17209
by: sushant | last post by:
hi why do we use '&' operator in scanf like scanf("%d", &x); but why not in printf() like printf("%d" , x); thnx in advance sushant
33
3179
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 ()
14
13815
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);
8
2378
by: Neil | last post by:
Hello Just to let you know this not homework, I'm learning the language of C on my own time.. I recently tried to create a escape for user saying printf ("Do you want to continue? (y or n)"); The scanf statement follows the prompt(printf above) which is the last statement in the while loop, before the "}"
3
9844
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 .
2
6555
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
9707
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
10586
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
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9161
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
7622
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
6856
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
5525
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...
2
3823
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2997
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.