Brand new to coding here. Tried to research this topic, but having difficulty finding where to start on questions I hardly know how to ask..
The following is a line of code I'm using in an online course and I'm trying to understand how gets() is working here. I am using Visual Studio in learning C, and the instructor is returning a different output (he is using CodeLite) when using gets(). For him, when he enters firstname in the command prompt in excess of 5 characters, the buffer will overflow the extra characters into the subsequent char variable, lastname. For me, when I enter in extra characters, my printf() will return exactly what I entered. For ex: If I enter firstname: George lastname: Washington, it will return "Hello, George, Washington.", where for him it would return "Hello, Georg, eWash."
Is Visual Studio performing some sort of flush on the buffer in between my gets()s? And what is the point of specifying '5' in char firstname[5] if when I enter more than 5 characters on the command prompt, it will store all the characters in my firstname and lastname char variables? Why would fgets() be a better solution in situations like this?
#include <stdio.h>
void flush_input(){
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
void getinput_with_gets() {
char firstname[5];
char lastname[5];
printf("Enter your first name:");
gets(firstname);
printf("Enter your last name:");
gets(lastname);
printf("Hello, %s, %s\n", firstname, lastname);
}
void getinput_with_fgets() {
char firstname[5];
char lastname[5];
printf("Enter your first name:");
fgets(firstname, 5, stdin);
printf("Enter your last name:");
// fflush(stdin); // This function may not (invariably) work with input!
flush_input();
fgets(lastname, 5, stdin);
flush_input();
printf("Hello, %s, %s\n", firstname, lastname);
}
int main(int argc, char **argv) {
getinput_with_gets();
// getinput_with_fgets();
return 0;
}