-2

I am trying to make a simple code in C, but i cant use the same variable:

#include <stdio.h>
#include <stdlib.h>


int main(){

    char a;

    printf("Type something\n");
    scanf("%c", &a);
    printf("%c", a);

    printf("\nType something else\n");
    scanf("%c", &a);

    printf("something else -> %c", a);
    return 0;
}

Any tips?

NoseKnowsAll
  • 4,593
  • 2
  • 23
  • 44
NoobCoder
  • 1
  • 1
  • 1
    When you say, you "can't use the same variable" what exactly is the problem? As far as I can see this should work, assuming you include `"\n"` in every one of your `printf` statements. – NoseKnowsAll Apr 13 '17 at 03:08
  • 1
    What do you mean _I can't use the same variable_? Are there compiler errors? What are your inputs, and outputs? – Tas Apr 13 '17 at 03:08
  • here printf("something else -> %c", a); i don't get nothing, is like i cant use the variable again (sorry about my english) – NoobCoder Apr 13 '17 at 03:12
  • 1
    You need to use `" %c"` in the format strings because `scanf()` leaves the newline in the input and the second `%c` doesn't skip white space (such as newlines) before reading a character. It's a common problem; there's a simple fix. – Jonathan Leffler Apr 13 '17 at 03:21
  • ow! thats fix the problem! – NoobCoder Apr 13 '17 at 03:24

1 Answers1

0

scanf will read your input character by character, for example:


You run the program, and type ab when it asks you for input, the output will be:

Type something
ab
a
Type something else
something else -> bPress any key to continue . . .

Note the b in last line.


If you type a then press Enter, the output will be:

Type something
a
a
Type something else
something else ->       // Note: there is a new line character here
Press any key to continue . . .
zhm
  • 3,513
  • 3
  • 34
  • 55