Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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. 😉

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading