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 ("\nDesplazamie nto en Tm?:\t");
scanf ("%f", &flota->desplazamiento );
printf ("\nCapacida d 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.desplazam iento,
flota.carga,
flota.eslora,
flota.tripulant es
);
}
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.desplazam iento,
flota.carga,
flota.eslora,
flota.tripulant es
);
}
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(respue sta) != 'n')
{
while (tolower(correc to) != 's')
{
alta (&barco);
imprime (datos, barco);
printf ("\nSon correctos los datos del buque (S o N)?: ");
scanf("%s", &correcto);
}
grabaFichero(fi chero, 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 2 2340
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
On Sat, 03 Apr 2004 00:15:22 +0200, Diego <da****@telefon ica.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>> This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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() should be called
during test.php's sleep, instead the first fgets blocks the processing
of the parent script and do_smth_else is called only once. How can I
do a non-blocking fgets()? I use php 4.3.4 on windows xp
$process = popen("c:\php\php...
|
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, two aspects which I want
to incorporate into my program eventually. That aside, my most
pressing problem right now is how to get rid of the newline in the
input when I use fgets(). Now I have looked around on the net, not so
much in this group...
|
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 fgets is ignored. I've been even tempted to use gets. Please,
|
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 standard says about fgets:
synopsis
#include <stdio.h>
char *fgets(char *s, int n, FILE *stream);
|
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 the program. Since fgets() doesn't return
the number of characters read it is pretty tough to handle
the embedded nulls once they are in the buffer.
So two questions:
1. Why did the folks who wrote fgets() have a successful
| |
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 following code comes from a discussion with Mark.
One of the purposes of SS is to produce fast-running programs
(compiling a subset of Python code to C++), to do this it accepts some
compromises in the type flexibility used by the programs, at the...
|
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 EOF/error), returns n-1 characters
plus
a appended null character.
|
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 default_buffer_length is changed from 4 --24 code
works fine.
But on the same line if I change the value of default_buffer_length
from 4 --10 and I get a memory error.
And if the change the value of the same variable from 4 --1024 bytes;
|
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/
specs
gcc version 2.95.3 20010315 (release)
|
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...
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |