Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly 'printf' an integer and a string in C?

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?

like image 396
user1420474 Avatar asked Jul 31 '12 02:07

user1420474


People also ask

What does %d and %S mean in C?

%s is for string %d is for decimal (or int) %c is for character.

Can you print a string with printf?

We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.

Can you print a string in C?

The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to directly print and read strings.


1 Answers

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.

like image 142
sblom Avatar answered Sep 22 '22 13:09

sblom