31

I have the following code:

char *s1, *s2;
char str[10];

printf("Type a string: ");
scanf("%s", str);

s1 = &str[0];
s2 = &str[2];

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:

A
�<�

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?

3
  • 1
    Another thing that people hadn't mentioned for a bit: please don't scanf into a limited-size buffer. The user can easily just type in more than the limit and screw your program over. (see also: buffer overflow attacks) Commented Jul 31, 2012 at 2:54
  • @DennisMeng: One can add a width specifier e.g. %123s. It is still potentially dangerous as that width doesn't include the null terminator. Commented Jun 7, 2014 at 10:54
  • @diapir True. The important bit is avoiding the buffer overflow. Commented Jun 7, 2014 at 20:10

3 Answers 3

44

You're on the right track. Here's a corrected version:

char str[10];
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:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh thanks so much!! didn't realize I can do this way. Thanks!
5

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.

1 Comment

Yeah, I realized that if I enter "ABCFS", it doesn't display garbage. I now know where the problem is. Thanks!
1

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.