473,889 Members | 1,394 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

scanf() vs gets()

OK I have 2 similar programmes, why does the first one work and the second does
not? Basically the problem is that the program seems to ignore the gets call if
it comes after a scanf call. Please anything even a hint would be really
helpful, I cant for the life of me see why the 2nd prog wont work...

gets before scanf

code:---------------------------------------------------------------------
-----------
#include <stdio.h>

int a;
char aaa[50];

main()
{
printf("Enter a string\n");
gets(aaa);
printf("%s\n",a aa);

printf("Enter a number\n");
scanf("%d",&a);
printf("%d",a);
}
--------------------------------------------------------------------------
------
scanf before gets
code:---------------------------------------------------------------------
-----------
#include <stdio.h>

int a;
char aaa[50];

main()
{
printf("Enter a number\n");
scanf("%d",&a);
printf("%d",a);

printf("Enter a string\n");
gets(aaa);
printf("%s\n",a aa);
}
Nov 13 '05
39 100831
"Teh Charleh" <on************ *@aol.comnojunk > wrote in message
news:20******** *************** ****@mb-m29.aol.com...
Why did you ignore Ben's (correct) advice to not use 'gets()'?
Wasnt ignoring it :)


He (and I) advised against its use. Your next post asked
how to continue to use it. Looks like you ignored it to me. :-)
just wanted to see how to get around the original problem
I was posed with (I found out about %*c, I think that ill do the job!)
It might, for a while. But try some more complex input, especially
intentionally invalid, and e.g. 'too long' input.
But hey
this short thread has greatly helped with my understanding of scanf,
Good.
gets
Only one thing need be understood about 'gets()': It should *NEVER*
be used. Ever.
and
the potential of fgets which is still 2 chapters away!
There's no law requiring you to read all text in a book
in sequential order. :-)

The vast majority of programming books for sale are simply incorrect.
< Someone should maybe think about writing a book that is actually

correct -Id

Many have. See www.accu.org as I've already advised.
buy it!
Use 'fgets()'.


From what Ive been hearing, it look as though fgets is definately the way
forward, thanks :)


It may be, it may not. It depends upon your goal. But 'fgets()'
can be used safely, 'gets()' cannot. (And it's not all that simple
to use 'scanf()' safely, either, but it can be done).
-Mike
Nov 13 '05 #11
Teh Charleh wrote:
*Never* use 'gets()'. Never, never, never, ever use it. Ever.

Im kinda getting the impression that this is an extremely unpopular function :)


Not really. And that's the problem. It's a function that shouldn't
exist, yet many people still use it. Look up the Morris Worm. This is
only one the earliest and most widely-known examples of gets() causing
serious problems. I doubt any single function/subroutine/procedure has
caused anywhere near as much damage and cost as much money as gets() has.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Nov 13 '05 #12
On 30 Nov 2003 20:28:41 GMT, in comp.lang.c ,
on************* @aol.comnojunk (Teh Charleh) wrote:

(please don't snip attributions, it helps keep posts sensible)

Ben pfaff wrote
By the way, don't use gets(). It cannot be used safely, except
by Dan Pop.


My book here C programming in easy steps is definately recommending it over
scanf if I want to input more than one word as a string!


Your C book is teaching you Bad C, probably because its an
introductory work.

gets() is a lethal function, rumoured to be responsible for more virus
propagations even than the Evil Empire. Don't use gets(). Use fgets(),
which is bufferlength safe, and then sscanf the string.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #13
Teh Charleh wrote:
.... snip ...
By the way, don't use gets(). It cannot be used safely, except
by Dan Pop.


My book here C programming in easy steps is definately recommending
it over scanf if I want to input more than one word as a string!


Never use gets. See the FAQ for reasons. Avoid scanf for
interactive work. You can use sscanf (or other routines) to parse
what a gets /replacement/ provides.

Any replacement for gets requires something extra from the
programmer to control it, such as supplying a buffer size
(fgets). Richard Heathfield has a readline routine, and I provide
a ggets() routine. ggets requires only that you supply the
address of a pointer, and eventually free the memory that pointer
points to. It is built upon the use of fgets. You can get the
source code and usage examples at:

<http://cbfalconer.att. net/download/>

Please tell us the name, author, publisher etc. of your C book so
that we can recommend burning it.

--
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 #14
Teh Charleh wrote:
This makes perfect sense and explains the behavior of my problem. This now
begs the question how do I go about telling gets() to ignore the newline
charecter input after the scanf...
By the way, don't use gets(). It cannot be used safely, except
by Dan Pop.


My book here C programming in easy steps is definately recommending it
over scanf if I want to input more than one word as a string!


Then your book was written by someone who is not very experienced in C. It
sounds like Herbert Schildt's handicraft, in fact.

See http://users.powernet.co.uk/eton/c/fgetdata.html for a more detailed
discussion of scanf, gets, fgets, and so on.

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #15
CBFalconer wrote:
Teh Charleh wrote:
... snip ...
> By the way, don't use gets(). It cannot be used safely, except
> by Dan Pop.


My book here C programming in easy steps is definately recommending
it over scanf if I want to input more than one word as a string!


Never use gets. See the FAQ for reasons. Avoid scanf for
interactive work. You can use sscanf (or other routines) to parse
what a gets /replacement/ provides.

Any replacement for gets requires something extra from the
programmer to control it, such as supplying a buffer size
(fgets). Richard Heathfield has a readline routine,


It's actually called fgetline(). I'll tell you what - I'll link to your page
if you link to mine. Deal?
and I provide
a ggets() routine. ggets requires only that you supply the
address of a pointer, and eventually free the memory that pointer
points to. It is built upon the use of fgets. You can get the
source code and usage examples at:

<http://cbfalconer.att. net/download/>
Hmmm. Seems to be down. I'll add the link once I know the exact page (which
I can't find out while the server is down, obviously - unless you tell me
here).
Please tell us the name, author, publisher etc. of your C book so
that we can recommend burning it.


Please hold the burn. The last two occasions I recall where someone said
something similar, the books in question turned out to be <cough> "C
Unleashed" and "The C Programming Language" and, in each case, the newbie
had misunderstood the book.

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #16
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:Wn******** ***********@new sread1.news.pas .earthlink.net. ..

return 0; /* main() is *required* to return an int */


No user defined function is actually _required_ to return a value in C90 or
C99, main() or otherwise.

Non-void function definitions in C90 are even allowed to use...

return;

....to exit. C99 [possibly C94/5?] added the criteria that non-void functions
must have an expression following the 'return', however the following subtle
weakness was left in:

"[For general functions,] If the } that terminates a function is reached,
and the value of the function call is used by the caller, the behavior is
undefined."

Although, in the case of a hosted environment main() definition, the return
value on reaching } is unspecified in C90, and 0 in C99.

All that said, typing return 0; in main isn't all that hard, especially
given the maximal robustness is supplies [broken historic implementations
notwithstanding .]

--
Peter
Nov 13 '05 #17
On Mon, 1 Dec 2003 20:22:04 +1100, in comp.lang.c , "Peter Nilsson"
<ai***@acay.com .au> wrote:
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:Wn******* ************@ne wsread1.news.pa s.earthlink.net ...

return 0; /* main() is *required* to return an int */


No user defined function is actually _required_ to return a value in C90 or
C99, main() or otherwise.


In c89, the relevant section of the standard said "It shall be defined
with a return type of int". Not much room there I feel for main() to
return other than an int. Lets not start another debate about the
meaning of the "or in some other..." part.

In c99, main is also required to return int. However if the user
suppplied code doesn't do it, then the compiler shall behave as though
zero were returned.

Snip stuff about nonvoid functions being able to return nothing. I
don't believe its quite valid but I'm not going to bother trawling
through the standard to prove it. Plus FWIW every compiler I've ever
used emits an error when a nonvoid function fails to return a value.
This is hardly conclusive, but strong circumstantial evidence.

And in any events, failing to return a value from a fn you explicitly
declared to return a value is just plain bad programming.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #18
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:pb******** *************** *********@4ax.c om...
On Mon, 1 Dec 2003 20:22:04 +1100, in comp.lang.c , "Peter Nilsson"
<ai***@acay.com .au> wrote:
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:Wn******* ************@ne wsread1.news.pa s.earthlink.net ...

return 0; /* main() is *required* to return an int */
No user defined function is actually _required_ to return a value in C90 orC99, main() or otherwise.


In c89, the relevant section of the standard said "It shall be defined
with a return type of int". Not much room there I feel for main() to
return other than an int.


I never said main could or should have a return type other than int. I said
it needn't return a value, i.e. it needn't have a return statement.

.... Snip stuff about nonvoid functions being able to return nothing. I
don't believe its quite valid but I'm not going to bother trawling
through the standard to prove it.
Well, ignorance is bliss...
Plus FWIW every compiler I've ever
used emits an error when a nonvoid function fails to return a value.
A 'diagnostic' I can understand, because implementations can emit those till
the cows come home. But if by 'error' you mean failed to translate the code,
then either you've failed to invoke your C compilers in conforming mode, or
you've only ever used broken C compilers.

[Note: C++ compilers are not C compilers.]
This is hardly conclusive, but strong circumstantial evidence.
You are correct, it's hardly conclusive at all.
And in any events, failing to return a value from a fn you explicitly
declared to return a value is just plain bad programming.


True, but it was quite common in K&R C:

blah() { puts("blah"); }
main() { blah(); }

The original C committee obviously decided not to break such code, although
why they didn't go the whole nine yards with C99, I don't know.

--
Peter
Nov 13 '05 #19
In <3F************ ***@yahoo.com> CBFalconer <cb********@yah oo.com> writes:
Teh Charleh wrote:

... snip ...
> By the way, don't use gets(). It cannot be used safely, except
> by Dan Pop.


My book here C programming in easy steps is definately recommending
it over scanf if I want to input more than one word as a string!


Never use gets. See the FAQ for reasons. Avoid scanf for
interactive work.


scanf is far better than fgets for interactive work.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #20

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

Similar topics

57
11803
by: Eric Boutin | last post by:
Hi ! I was wondering how to quickly and safely use a safe scanf( ) or gets function... I mean.. if I do : char a; scanf("%s", a); and the user input a 257 char string.. that creates a problem.. same for gets.. even if you create a char array that's 99999999999999 char long.. if the user input something longer it will still be a bug.. and I don't want
12
9881
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
1774
by: sajjanharudit | last post by:
Can anyone explain me what is happening in the following code: #include<stdio.h> int main() { int i,j; scanf("%d %d" + scanf("%d %d",&i,&j)); printf("%d %d\n"); }
51
3961
by: moosdau | last post by:
my code: do { printf("please input the dividend and the divisor.\n"); if(!scanf("%d%d",&dend,&dor)) { temp1=1; fflush(stdin); } else
185
17585
by: Martin Jørgensen | last post by:
Hi, Consider: ------------ char stringinput ..bla. bla. bla. do {
26
4549
by: tesh.uk | last post by:
Hi Gurus, I have written the following code with the help of Ivor Horton's Beginning C : // Structures, Arrays of Structures. #include "stdafx.h" #include "stdio.h" #define MY_ARRAY 15
280
9053
by: jacob navia | last post by:
In the discussion group comp.std.c Mr Gwyn wrote: < quote > .... gets has been declared an obsolescent feature and deprecated, as a direct result of my submitting a DR about it (which originally suggested a less drastic change). (The official impact awaits wrapping up the latest batch of TCs into a formal amending document, and getting it approved and published.)
19
2164
by: subratasinha2006 | last post by:
I can not accept a string (without space) of length more than 127 whatever I do.. Entry is restricted by 127 characters. I have declared an array of size more than 200. or I have used dynamic memory allocation. But the echo is stopped
12
1639
by: non star | last post by:
i have a project that i'm working on and i faces this problem that gets in line 123 isn't work note: the project should be totally in c #include <stdlib.h> #include <stdio.h> #define size 1000000 #include <string.h> void add_fractions (int a, int b, int c, int *d, int *ansn, int *ansd); void subtract_fractions (int a, int b, int c, int *d, int *ansn, int *ansd);
0
9961
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
10784
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
10887
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
9602
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
7991
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
7148
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
5825
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
6021
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4642
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.