Storing a character in the vector

Asked

Viewed 66 times

3

For some reason, the program is not keeping the character in the vector, as it should be stored, it is skipping the first character. For example:

// Declarando o vetor

char novosValores[4] = {0};

scanf("%c %c %c %c", &novosValores[0], &novosValores[1], &novosValores[2], &novosValores[3]);

Follow the image: inserir a descrição da imagem aqui

  • 1

    Just for a space before the first %c. Since you didn’t, he’s reading the line break and putting in the first character

  • What code is on top of the scanf("%c %c %c %c" , ...) ? There are other readings made with scanf ? if yes which ?

  • Thank you very much, it helped a lot!

  • No, Isac, thanks for commenting.

  • If you managed to solve it this way, take advantage and put the solution as an answer to help other people who have the same problem.

1 answer

1

The scanf function uses a buffer to obtain input. The user entering input into a terminal is stored in a buffer. The scanf function reads the characters of that buffer.

What happens in your example is that you are entering, after 4, the string

"\nE C A F\n"

So the first character that scanf reads is '\n'.

A blank space in the format of the scanf, tells the function to skip white space "whitespace" (\n \r tabs spaces, etc.). This way, you should start the string the format with a blank space to skip the "whitespace" and read the Character you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.