0

In my program I must store input characters in variables and then add them to arrays. But is there a way to use the same variable each time?

char str1,str2;
printf("insert character");
scanf("%c",&str1);
printf("%c",str1);

printf("insert character");
scanf("%c",&str2);
printf("%c",str2);   

I would like to do something like this but using one variable. Also can I use scanf more than 1 times? It seems the executable stops before the second character is given.

peterh
  • 11,875
  • 18
  • 85
  • 108
core_break
  • 11
  • 3
  • 1
    Do you mean you haven't tried `scanf("%c",&str1); printf("%c",str1); scanf("%c",&str1); printf("%c",str1);`?! Or do you want something else. It stops probably because you didn't consume a new line after the 1st one. Relevant: http://stackoverflow.com/a/4129460/1133179. – luk32 May 12 '14 at 13:10
  • Not getting what the problem is actually. Can you show the whole code? – Anmol Singh Jaggi May 12 '14 at 13:11
  • 2
    Please provide some more context on the actual problem you are trying to solve. Are you familiar with `fgets(3)`/`getc(3)`? – wkz May 12 '14 at 13:16
  • 1
    Replace `printf("%c",strX);` with `printf("'%c'",strX);` and have a close look at the result. – alk May 12 '14 at 13:24
  • Note: recommend to check the result of `scanf()`. Is it `1` as expected? Better yet, use `int ch = fgetc(stdin)` if code only needs to read 1 `char`. – chux - Reinstate Monica May 12 '14 at 15:09

1 Answers1

0

Yes, you can use scanf() more than once. Your problem is not actually because of scanf();, Its with your input, To give input for first scanf() in your program, what we naturally do is we type(through keyboard) a character and hit ENTER KEY,Under the hood when you hit ENTER KEY a '\n' character is produced which is read by your second scanf() ,that's why your second scanf() is not waiting for input from you as you expected, You need to clear this '\n' manually when you use %c.(when %d %f %s are used '\n' are automatically removed that's why we don't face this problem when using them).

To solve problem you can use "%c" like this " %c" (note space before %c, this skips '\n' characters) 

scanf(" %c",&str1);
printf("%c",str1);
//code to add them to array's  
scanf(" %c",&str1);//Have Re-Used the same variable str1. 
printf("%c",str1);
Mysterious Jack
  • 621
  • 6
  • 18