Quindi io con fgets avro sempre un carattere in piu rispetto alla lunghezza effettiva della stringa?Perché fgets() lascia il carattere di ritorno nella stringa, che se non serve deve essere eliminato
Se è presente il carattere \n allora fgets lo leggerà. Lo puoi rimuovere come ha detto @Andretti60 . Basta che ti calcoli la lunghezza della stringa e fai str[len - 1] = '\0' (lo rimpiazzi con il carattere di fine stringaQuindi io con fgets avro sempre un carattere in piu rispetto alla lunghezza effettiva della stringa?
Ma quindi nella stringa letta con fgets alla fine c'è il carattere di new line se io premo invio, ma altrimenti non è presente il carattere /0?Se è presente il carattere \n allora fgets lo leggerà. Lo puoi rimuovere come ha detto @Andretti60 . Basta che ti calcoli la lunghezza della stringa e fai str[len - 1] = '\0' (lo rimpiazzi con il carattere di fine stringa
Attento a come usi la gets perchè la gets è causa di Buffer overflow
E invece gets non mette niente alla fine della stringa? Nemmeno /0?Ma quindi nella stringa letta con fgets alla fine c'è il carattere di new line se io premo invio, ma altrimenti non è presente il carattere /0?
Inviato da Redmi 5 Plus tramite App ufficiale di Tom\'s Hardware Italia Forum
Dal manuale:E invece gets non mette niente alla fine della stringa? Nemmeno /0?
Inviato da Redmi 5 Plus tramite App ufficiale di Tom\'s Hardware Italia Forum
gets() reads a line from stdin into the buffer pointed to by s
until either a terminating newline or EOF, which it replaces with
a null byte ('\0'). No check for buffer overrun is performed
(see BUGS below).
The fgets() function shall read bytes from stream into the array
pointed to by s until n-1 bytes are read, or a <newline> is read
and transferred to s, or an end-of-file condition is encountered.
A null byte shall be written immediately after the last byte read
into the array. If the end-of-file condition is encountered
before any bytes are read, the contents of the array pointed to
by s shall not be changed.
The fgets() function may mark the last data access timestamp of
the file associated with stream for update. The last data access
timestamp shall be marked for update by the first successful
execution of fgetc(), fgets(), fread(), fscanf(), getc(),
getchar(), getdelim(), getline(), gets(), or scanf() using stream
that returns data not supplied by a prior call to ungetc().
Va bene capito, grazieDal manuale:
fgets invece
Puoi fare una prova ed esamini la stringa e vedi cosa accade :)Va bene capito, grazie
Inviato da Redmi 5 Plus tramite App ufficiale di Tom\'s Hardware Italia Forum