1

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

moyoloco09
  • 13
  • 3
  • Better to use `fgets(b, sizeof b, stdin);`. Keep in mind that with user input you may have to content with the newline, and don't forget to allow room for the null terminator in your buffer. As is you only have room for 3 characters of user input. – ryyker Nov 17 '22 at 20:07
  • Suggested read: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Bob__ Nov 17 '22 at 20:09
  • `gets` was removed from `C11`, so that could be causing some confusion in your validator. – Neil Nov 17 '22 at 20:15
  • Does this answer your question? [scanf() leaves the newline character in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-newline-character-in-the-buffer) – Andreas Wenzel Nov 17 '22 at 21:24

1 Answers1

4

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    +1 for providing yet another great example of why `scanf()` should never be preferred over eg. `fgets()` when performing user input tasks. The rules to use `scanf` correctly are varied, complicated and error prone. – ryyker Nov 17 '22 at 20:14
  • This was giving me headaches for days. Thank you very much. That done it. – moyoloco09 Nov 17 '22 at 21:00