I have this code that is supposed to cut the string the user inputs at 256 characters and prevent it from "spilling" into susequent fgets() functions. It worked perfectly up until today.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include <ctype.h>
#include <string.h>
int main(){
printf("\nEnter a new string.\n");
char string[256];
do
{
fgets(string,256,stdin);
} while (strlen(string) > 0 && string[strlen(string) - 1] != '\n');
printf("\n\n stringa %s\n", string);
}
So for example if I input a string longer than 256 characters like
Qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm
i would expect it to print:
Qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxc
but instead it prints:
cvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm
Why is this? How can I fix it?
CodePudding user response:
fgets will read until the buffer is full or it hits EOL (\n).
The loop in your code will call fgets until the result includes the EOL. So: first time through it reads the buffer until full, and then continues the loop; second time through it reads from the current point until it hits the EOL. That's what's in the result.
You should always check the return value of fgets. The loop will never exit if the input doesn't contain an EOL.
the buffer size passed to fgets includes the returned \0 so you are reading 255 characters, not 256.
If you want to read 256 characters and then throw away input until \n, then do that:
char string[257]; /* room for 256 \0 */
string[0] = 0; /* set string empty in case of no input */
if (fgets(string, sizeof(string), stdin)) { /* read */
if (!strchr(string, '\n')) { /* didn't pick up EOL */
do {
int c = fgetc(stdin); /* get characters */
} while (c >= 0 && c != '\n'); /* until EOL or EOF */
}
}