-6

Today i have been coding a came across with this code:

Code

#include <stdio.h>

main() {

    char letra1;
    char letra2;

    printf("Primera letra: ");
    scanf("%c", &letra1);
    printf("Segunda letra: ");
    scanf("%c", &letra2);

}

When I execute the code the first scanf() executes well but the second even didn't execute and close the program and I don't know why.

Execution

> ej3
Primera letra: A
Segunda letra: 

Thanks for your time guys.

Glenn Tinoco
  • 11
  • 1
  • 2
  • 2
    Post your code, input, output and expected output here. Without that, your post is unclear. – chux - Reinstate Monica Jul 05 '17 at 22:14
  • Add the code to your question. There's no need to upload an image for that since SO supports code posting and formatting as part of your question. – woz Jul 05 '17 at 22:14
  • 1
    `"%c"` --> ``" %c"`` – BLUEPIXY Jul 05 '17 at 22:15
  • It's jut that the second scanf doesnt execute and just printf() and close the program – Glenn Tinoco Jul 05 '17 at 22:15
  • How do you know that the first scanf() call "executes well" if you don't print anything out afterwards? edit: didn't see that execution screenshot. Whoops – SaxyPandaBear Jul 05 '17 at 22:15
  • The problem is solved with the " %c". – Glenn Tinoco Jul 05 '17 at 22:17
  • 1
    You can accept the answer by clicking on the grey checkmark below its score. But please do post the actual code for your program: cut from your editor, paste into the question body, select the code and type Alt-K to indent it. – chqrlie Jul 05 '17 at 22:18
  • Don't post your code as an image. – klutt Jul 05 '17 at 22:31
  • 1
    The `scanf()` function is a brute to foist on novice programmers. See [Beginners Guide Aware from `scanf()`](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) for some discussion. Don't be upset that you find it hard to use — it is hard to use. – Jonathan Leffler Jul 05 '17 at 22:40

1 Answers1

1

You should use a scanf format string " %c" to skip any pending whitespace characters, including the newline the user typed after the first letter. As posted, the second scanf() reads the \n that is pending in the input stream, so it does not wait for user input.

chqrlie
  • 131,814
  • 10
  • 121
  • 189