I want to input valors for a and b, being a an int and b a str. When I run my program I can input a valor, but then it ingnores printf() and gets() for b.
#include<stdio.h>>
int main()
{
int a;
char b[5];
printf("Write a:\n");
scanf("%i", &a);
printf("Write b:\n");
gets(b);
printf("a = %i, b = %s", a, b);
return 0;
}
In the end, it just prints:
a = (valor written), b =
I don't know what's wrong with this, neither if it's a different way to get this working. I'm pretty new with C. Thank you in advance. ;)
The function
getsis unsafe and is not supported by the C Standard. Instead use eitherscanforfgets.As for your problem then after this call of
scanfthe input buffer contains the new line character
'\n'that corresponds to the pressed key Enter. And the following call ofgetsreads an empty string by encountering the new line character.Instead of using
getswritePay attention to the leading space in the format string. It allows to skip white space characters as for example the new line character
'\n'. And the call ofscanfcan read a string with maximum length equal to 4. If you want to read a larger string then enlarge the arrayband the field width specifier in the format string.