I have the following code:
char *s1, *s2; char str; printf("Type a string: "); scanf("%s", str); s1 = &str; s2 = &str; printf("%s\n", s1); printf("%s\n", s2);
When I run the code, and enter the input "A 1" as follow:
Type a string: A 1
I got the following result:
I'm trying to read the first character as a string and the third character as an integer, and then print those out on the screen. The first character always works, but the screen would just display random stuffs after that.... How should I fix it?
This question is tagged with
~ Asked on 2012-07-31 02:46:31
You're on the right track. Here's a corrected version:
char str; int n; printf("type a string: "); scanf("%s %d", str, &n); printf("%s\n", str); printf("%d\n", n);
Let's talk through the changes:
n) to store your number in
scanfto read in first a string and then a number (
%dmeans number, as you already knew from your
That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow
str and start trampling your stack.
~ Answered on 2012-07-31 02:50:08
scanf("%s",str) scans only until it finds a whitespace character. With the input
"A 1", it will scan only the first character, hence
s2 points at the garbage that happened to be in
str, since that array wasn't initialised.
~ Answered on 2012-07-31 02:51:04