473,889 Members | 1,387 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 100832
on************* @aol.comnojunk (Teh Charleh) wrote in message news:<20******* *************** *****@mb-m29.aol.com>...
Why did you ignore Ben's (correct) advice to not use 'gets()'?


Wasnt ignoring it :) 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!) But hey
this short thread has greatly helped with my understanding of scanf, gets and
the potential of fgets which is still 2 chapters away!

The vast majority of programming books for sale are simply incorrect.

< Someone should maybe think about writing a book that is actually correct -Id

buy it!
Use 'fgets()'.


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


Just be aware of the following:

1. fgets() will only read as many characters as you specify. If the
user typed in more characters than that, you'll have to be able to
detect that condition and recover from it, either by discarding the
remaining input (another call to fgets()) or by writing to a
dynamically resizable buffer.

2. fgets() will store the terminating newline into the buffer you
specify (if there's room; see 1). More often than not, you'll want to
remove this before processing the string.
Nov 13 '05 #21
On Mon, 1 Dec 2003 23:22:34 +1100, in comp.lang.c , "Peter Nilsson"
<ai***@acay.com .au> wrote:
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:pb******* *************** **********@4ax. com...
On Mon, 1 Dec 2003 20:22:04 +1100, in comp.lang.c , "Peter Nilsson"
>
>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.


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.


My misunderstandin g. I understood your remark above to mean "you don't
have to return anything even if you declare the function to return
something".
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.
True.
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.
This is a nonargument. No conforming compiler is *required* to fail to
translate, except when seeing the #error preprocessor command, or a
something like a syntax error. Many many examples of undefined
behaviour will invoke no diagnostic at all, never mind stopping the
compile.

BTW to get this diagnostic, I invoked my compilers in the most fully
conforming mode available. Do you assert that *every* C compiler is
broken in this respect?
[Note: C++ compilers are not C compilers.]


Gee ! : -)
This is hardly conclusive, but strong circumstantial evidence.


You are correct, it's hardly conclusive at all.


*shrug*. You're twisting the english language to make a clever remark.
Hardly germane to the discussion.
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:


K&R C doesn't conform to ANSI/ISO. Plus I need hardly remind you that
a book, no matter who it is by, is no more conclusive proof than is a
compiler (pace of course ISO/IEC 9899:1999 or whatever its ID is).

--
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 #22
Richard Heathfield wrote:
CBFalconer wrote:

.... snip ...

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).


I goofed. The URL is:

<http://cbfalconer.home .att.net/download/ggets.zip>
^^^^^^

with the actual file name only needed to avoid viewing the page.
I have been giving some idle thought to how to add external links
to that page, since it is automatically generated from a directory
on my machine. I am extremely lazy.

--
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 #23
In <43************ **************@ posting.google. com> jo*******@my-deja.com (John Bode) writes:
Just be aware of the following:

1. fgets() will only read as many characters as you specify. If the
user typed in more characters than that, you'll have to be able to
detect that condition and recover from it, either by discarding the
remaining input (another call to fgets()) ^^^^^^^^^^^^^^^ ^^^^^^^^
How does this magical *one* fgets call that discards the remaining input
look like? This is a trivial job for [f]scanf, but I wasn't aware that
fgets can do it, too.
or by writing to a dynamically resizable buffer.
In which case, it's simpler not to mess with fgets at all.
2. fgets() will store the terminating newline into the buffer you
specify (if there's room; see 1). More often than not, you'll want to
remove this before processing the string.


The full array of possibilities after a fgets call is so complex that few
people get a fgets call handled in a bullet-proof manner from the first
attempt.

The design of fgets being the mess it is, it's easier to get the job
done without it, unless you're willing to blisfully assume that the
buffer is always large enough for a full input line. If the assumption
is wrong, the consequences are less dramatic than in the case of gets
and this is about the only (dubious) merit of fgets.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #24
In <3f******@news. rivernet.com.au > "Peter Nilsson" <ai***@acay.com .au> writes:
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:pb******* *************** **********@4ax. com...
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.


Or he's talking (writing) nonsense, as usual.

fangorn:~/tmp 335> cat test.c
int main(void) { }
fangorn:~/tmp 336> gcc test.c
fangorn:~/tmp 337> icc test.c
test.c
fangorn:~/tmp 338> pgcc test.c
fangorn:~/tmp 339>

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

In <43************ **************@ posting.google. com> jo*******@my-deja.com (John Bode) writes:
Just be aware of the following:

1. fgets() will only read as many characters as you specify. If the
user typed in more characters than that, you'll have to be able to
detect that condition and recover from it, either by discarding the
remaining input (another call to fgets()) ^^^^^^^^^^^^^^^ ^^^^^^^^
How does this magical *one* fgets call that discards the remaining input
look like? This is a trivial job for [f]scanf, but I wasn't aware that
fgets can do it, too.
or by writing to a dynamically resizable buffer.


In which case, it's simpler not to mess with fgets at all.
2. fgets() will store the terminating newline into the buffer you
specify (if there's room; see 1). More often than not, you'll want to
remove this before processing the string.


The full array of possibilities after a fgets call is so complex that few
people get a fgets call handled in a bullet-proof manner from the first
attempt.

The full array of possibilities after a call to fgets() are three.

1. fgets() returns NULL. You are probably at end-of-file. Check.

2. fgets() returns a string terminated like "...\n\0". Perfect.

3. fgets() returns a string like "...\0" without the '\n' newline.
This is the only 'interesting' case. Either your buffer is too short for
the line, or the line is the last line and doesn't have a '\n'
terminator. Assume the former and realloc the buffer with more room. Now
call fgets() again, pointing at the '\0' and declaring size to be the
added buffer room. You will achieve results 1, 2 or 3. Lather, Rinse,
Repeat. :=)
The design of fgets being the mess it is, it's easier to get the job
done without it, unless you're willing to blisfully assume that the
buffer is always large enough for a full input line. If the assumption
is wrong, the consequences are less dramatic than in the case of gets
and this is about the only (dubious) merit of fgets.

I don't see that fgets() is a mess but that's your call if you want to
make it.
--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #26
Da*****@cern.ch (Dan Pop) wrote in message news:<bq******* ***@sunnews.cer n.ch>...
In <43************ **************@ posting.google. com> jo*******@my-deja.com (John Bode) writes:
Just be aware of the following:

1. fgets() will only read as many characters as you specify. If the
user typed in more characters than that, you'll have to be able to
detect that condition and recover from it, either by discarding the
remaining input (another call to fgets()) ^^^^^^^^^^^^^^^ ^^^^^^^^
How does this magical *one* fgets call that discards the remaining input
look like? This is a trivial job for [f]scanf, but I wasn't aware that
fgets can do it, too.


Additional calls to fgets() or other input routine of your choice.
Better?
or by writing to a dynamically resizable buffer.
In which case, it's simpler not to mess with fgets at all.
2. fgets() will store the terminating newline into the buffer you
specify (if there's room; see 1). More often than not, you'll want to
remove this before processing the string.


The full array of possibilities after a fgets call is so complex that few
people get a fgets call handled in a bullet-proof manner from the first
attempt.


Which is why you wrap fgets() in a lot of other logic to build robust
I/O routines.
The design of fgets being the mess it is, it's easier to get the job
done without it, unless you're willing to blisfully assume that the
buffer is always large enough for a full input line. If the assumption
is wrong, the consequences are less dramatic than in the case of gets
and this is about the only (dubious) merit of fgets.

Dan


No, fgets() isn't a magic bullet. Neither is *scanf(). All C I/O
routines suck in their own special way. All require more support
logic than they should.
Nov 13 '05 #27
dam
You can add a statement fflush(stdin) after scanf. It will clear the input
buffer and the gets work properly.

Regards
shun
"Teh Charleh" <on************ *@aol.comnojunk > ¼¶¼g©ó¶l¥ó·s»D
:20************ *************** @mb-m29.aol.com...
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 #28
CBFalconer wrote:
Richard Heathfield wrote:
CBFalconer wrote:

... snip ...

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).


I goofed. The URL is:

<http://cbfalconer.home .att.net/download/ggets.zip>
^^^^^^

with the actual file name only needed to avoid viewing the page.
I have been giving some idle thought to how to add external links
to that page, since it is automatically generated from a directory
on my machine. I am extremely lazy.


I added something into the link to ggets on the download page. It
is not a link, because the auto creation software won't handle
that, but it is cut and pastable into a link.

--
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 #29
dam wrote:
You can add a statement fflush(stdin) after scanf.
No, you can't. fflush only works on streams open for output or update.
Calling it on input streams invokes undefined behaviour.
It will clear the
input buffer
The Standard offers no such guarantee.
and the gets work properly.


How will you protect the array from overflow?

--
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 #30

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
11188
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
10785
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
10439
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
9603
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();...
1
4644
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
3
3253
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.