My main problem here is that I have two strings and a float to read. The strings' size is 10 bytes, but I should be able to read no matter what input it is and store it inside the strings.
For example:
if my input is Hello world!
then the string should be string = "Hello wor"
if my input is Hello
then the string should be string = "Hello"
Now you might think this is obvious, just use fgets right? But that presents buffer problems when reading a second string. The thing is, I did find a fix, but that involves using the fflush function, but it appears that it doesn't work in a few compilers.
I searched for an alternative and found while ( getchar() != '\n')
but it actually doesn't work like fflush.
So what I'm asking here is there's a better alternative to read a string no matter the length of the input? This is what I came up with:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
char nom[10] , prenom[10];
double salaire;
fgets( nom , sizeof( nom ) , stdin );
nom[ strcspn( nom , "\n") ] = 0;
fflush(stdin);
fgets( prenom , sizeof( prenom ) ,stdin );
prenom[ strcspn( prenom , "\n") ] = 0;
fflush(stdin);
scanf("%lf",&salaire);
printf("%s\n",nom);
printf("%s\n",prenom);
printf("%lf\n",salaire);
return 0;
}