Home > Enterprise >  Why my program doesn't allow me to input b?
Why my program doesn't allow me to input b?

Time:11-18

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. ;)

CodePudding user response:

The function gets is unsafe and is not supported by the C Standard. Instead use either scanf or fgets.

As for your problem then after this call of scanf

scanf("%i", &a);

the input buffer contains the new line character '\n' that corresponds to the pressed key Enter. And the following call of gets reads an empty string by encountering the new line character.

Instead of using gets write

scanf( " %4[^\n]", b );

Pay 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 of scanf can read a string with maximum length equal to 4. If you want to read a larger string then enlarge the array b and the field width specifier in the format string.

  • Related