473,394 Members | 1,774 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

fgets and variants

Hi,

Using gcc 2.96

This message was suggested by a thread started by Knak on 21/03/04

The question is:

When I run the following code, if I want to introduce a second pile of
data, the fgets is ignored. I've been even tempted to use gets. Please,
compile and try.

I've tested fgets, and a simulation of fgets suggested in the cited
thread. It's quite frustrating to seeall my efforts working one time and
failing when calling fgets a second time from the samefunction.

Please look at the following piece of code. First is a small
program (just the beginning of an exercise, not veryfing any user input),
and then following a variation picked up from the above
cited thread. (Thanks to Minti, isingh AT acm DOT org).

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

typedef struct buque /* El nombre buque no sirve aqu de nada, solo como recordatorio */
{
char nombre[41];
float desplazamiento; /* Toneladas */
float carga; /* Capacidad de carga, toneladas */
float eslora; /* metros */
unsigned short int tripulantes; /* Nmero de tripulantes */
} buque; /* Asigna el tipo struct a buque mediante el typedef */

void alta (buque * flota) /* Si no declaramos un puntero al struct, no pasa los datos
durante la ejecucin de la funcin*/
{
char nbarco[41];

printf ("\n*************ALTA DE BUQUES****************\n\n");

printf ("\nNombre del buque?:\t");
fgets(nbarco, 41, stdin); /* aade newline al final */
//fgets(nbarco, strlen(nbarco), stdin); /* quita un carcter al final */
strcpy( flota->nombre, nbarco );

printf ("\nDesplazamiento en Tm?:\t");
scanf ("%f", &flota->desplazamiento);

printf ("\nCapacidad de carga en Tm?:\t");
scanf ("%f", &flota->carga);

printf ("\nEslora en mts?:\t");
scanf ("%f", &flota->eslora);

printf ("\nNmero de tripulantes.?:\t");
scanf ("%d", &flota->tripulantes);

}

void grabaFichero (FILE *fp, char* formato, buque flota)
{
formato = "\n\
Nombre del buque: \t%-40s\n\
Desplazamiento: \t%6.2f Tm\n\
Carga: \t\t%6.2f Tm\n\
Eslora: \t\t%4.2f mts\n\
Tripulacin: \t%4d\n\n";

fprintf (fp,
formato,
flota.nombre,
flota.desplazamiento,
flota.carga,
flota.eslora,
flota.tripulantes
);
}

void imprime (char * formato, buque flota)
{
formato = "\n\
Nombre del buque: \t%-40s\n\
Desplazamiento: \t%6.2f Tm\n\
Carga: \t\t%6.2f Tm\n\
Eslora: \t\t%4.2f mts\n\
Tripulacin: \t%4d\n\n";

printf ( formato,
flota.nombre,
flota.desplazamiento,
flota.carga,
flota.eslora,
flota.tripulantes
);
}

int main()
{
buque barco;
char * datos;
char correcto = 'n';
char respuesta = 's';

FILE *fichero;
while (NULL == (fichero = fopen("naviera.txt", "a+"))) /* si naviera.txt existe, lo abre
y si no lo crea*/
{
printf ("\nError al abrir el fichero de buques\n");
return -1;
}

while (tolower(respuesta) != 'n')
{
while (tolower(correcto) != 's')
{
alta (&barco);
imprime (datos, barco);
printf ("\nSon correctos los datos del buque (S o N)?: ");
scanf("%s", &correcto);
}

grabaFichero(fichero, datos, barco);
printf ("\nDar de alta ms buques (S o N)?: ");
scanf("%s", &respuesta);
}

fclose(fichero);

return 0;
}

_______________________

Following the variation tested, getting the same result:
(replaces the 1st paragraph following ***Alta....., and of course I've included
the #define VERDAD 1)
int tamano = 1;
char* nbarco = ( char * ) malloc( tamano );
int i = 0;
int c;
while ( VERDAD ) {
c = getchar();
if ( c == '\n' || c == EOF ) { nbarco[i] = '\0' ; break; }
else {
if ( i == tamano ) {
nbarco = ( char * ) realloc ( nbarco, tamano *= 2 );
if ( ! nbarco ) {
exit ( EXIT_FAILURE );
}
}
nbarco[i++] = c;
}
}

Thanks very much for your help,
Diego
damulco AT telefonica DOT net
Nov 14 '05 #1
2 2318
in comp.lang.c i read:
When I run the following code, if I want to introduce a second pile of
data, the fgets is ignored.
actually it's your lack of understanding of how scanf works and too little
debugging (skill?) that is causing you to think that the second fgets is
being ignored. scanf examines each byte on the input stream, as soon as it
reaches one that no longer is acceptable for the type of conversion being
performed it puts it back onto the stream and finalizes the conversion.
you are probably pressing enter (i.e., '\n') after each of the values. the
%d's have no use for '\n' so it is left on the input stream, and since %d
skips leading whitespace it's not a problem for scanf, but when all your
%d's are done then whatever stopped the last conversion (probably a '\n')
is left on the stream. the second fgets terminates copying as soon as it
copies a '\n' (or one less than the limit), which is likely the first thing.
char nbarco[41]; fgets(nbarco, 41, stdin); /* aade newline al final */
//fgets(nbarco, strlen(nbarco), stdin); /* quita un carcter al final */


since nbarco is an automatic variable without an initializer and not
otherwise assigned prior to this point you cannot use strlen() safely.
further i'm not sure why you would want to read at most as many characters
as the string already happens to contain. the first is the correct usage
of fgets, though i'd probably use sizeof nbarco instead of the `magic'
value 41 -- it's too easy for them to get out of sync otherwise.

--
a signature
Nov 14 '05 #2
On Sat, 03 Apr 2004 00:15:22 +0200, Diego <da****@telefonica.net>
wrote:
Hi,

Using gcc 2.96

This message was suggested by a thread started by Knak on 21/03/04

The question is:

When I run the following code, if I want to introduce a second pile of
data, the fgets is ignored. I've been even tempted to use gets. Please,
compile and try.

I've tested fgets, and a simulation of fgets suggested in the cited
thread. It's quite frustrating to seeall my efforts working one time and
failing when calling fgets a second time from the samefunction.

Please look at the following piece of code. First is a small
program (just the beginning of an exercise, not veryfing any user input),
and then following a variation picked up from the above
cited thread. (Thanks to Minti, isingh AT acm DOT org).


If you are going to use scanf and fgets together, you must make sure
that after calling scanf you remove the '\n' that is left in the
stream. Otherwise, the next time you call fgets it reads that
character and believes it is all done.

<<Remove the del for email>>
Nov 14 '05 #3

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

Similar topics

6
by: Tanel | last post by:
Hello, I need to read a result of the first script (that takes some time to run) from the second script so that the first script doesn't block the second. Here is a short example. do_smth_else()...
5
by: Rob Somers | last post by:
Hey all I am writing a program to keep track of expenses and so on - it is not a school project, I am learning C as a hobby - At any rate, I am new to structs and reading and writing to files,...
2
by: Diego | last post by:
Hi, Using gcc 2.96 This message was suggested by a thread started by Knak on 21/03/04 The question is: When I run the following code, if I want to introduce a second pile of data, the...
20
by: TTroy | last post by:
Hello, I have found some peculiar behaviour in the fgets runtime library function for my compiler/OS/platform (Dev C++/XP/P4) - making a C console program (which runs in a CMD.exe shell). The...
35
by: David Mathog | last post by:
Every so often one of my fgets() based programs encounters an input file containing embedded nulls. fgets is happy to read these but the embedded nulls subsequently cause problems elsewhere in...
2
by: bearophileHUGS | last post by:
Notes: - This email is about Mark Dufour's Shed Skin (SS) (http://shed-skin.blogspot.com), but the errors/ingenuousness it contains are mine. My experience with C++ is limited still. - The...
11
by: santosh | last post by:
Hi, A book that I'm currently using notes that the fgets() function does not return until Return is pressed or an EOF or other error is encountered. It then at most (in the absence of...
32
by: FireHead | last post by:
Hello C World & Fanatics I am trying replace fgets and provide a equavivalant function of BufferedInputReader::readLine. I am calling this readLine function as get_Stream. In the line 4 where...
285
by: Sheth Raxit | last post by:
Machine 1 : bash-3.00$ uname -a SunOS <hostname5.10 Generic_118822-30 sun4u sparc SUNW,Sun-Fire-280R bash-3.00$ gcc -v Reading specs from /usr/local/lib/gcc-lib/sparc-sun-solaris2.8/2.95.3/...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.