Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using %s in C correctly - very basic level

Tags:

c

I know that %s is a string of characters, but I don't know how to use it. Can anyone provide me a very basic example of how its used and how its different from char ?


(edited)

i'm 2 weeks into this course, it's my first time programming. I'm not allowed to use material that hasn't been taught yet on the assignments, so that's why I asked. I have a few books on C and have googled but still wasn't sure, so I asked. (thanks for all the down-votes) All the examples given below use arrays which hasn't been taught yet, so I'm assuming I can't use %s yet either. Thanks.

like image 532
nofe Avatar asked Apr 02 '12 17:04

nofe


4 Answers

For both *printf and *scanf, %s expects the corresponding argument to be of type char *, and for scanf, it had better point to a writable buffer (i.e., not a string literal).

char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";

printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);

scanf("%55s", str_buf);

Using %s in scanf without an explcit field width opens the same buffer overflow exploit that gets did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf, you can't supply the field with as a run time argument:

printf("%*s\n", field_width, string);

One option is to build the format string dynamically:

char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"

EDIT

Using scanf with the %s conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like

"This is a test"

then scanf("%55s", str_buf) will read and assign "This" to str_buf. Note that the field with specifier doesn't make a difference in this case.

like image 94
John Bode Avatar answered Nov 01 '22 23:11

John Bode


Here goes:

char str[] = "This is the end";
char input[100];

printf("%s\n", str);
printf("%c\n", *str);

scanf("%99s", input);
like image 41
cnicutar Avatar answered Nov 01 '22 23:11

cnicutar


%s will get all the values until it gets NULL i.e. '\0'.

char str1[] = "This is the end\0";
printf("%s",str1);

will give

This is the end

char str2[] = "this is\0 the end\0";
printf("%s",str2);

will give

this is

like image 39
Froyo Avatar answered Nov 01 '22 22:11

Froyo


void myfunc(void)
{
    char* text = "Hello World";
    char  aLetter = 'C';

    printf("%s\n", text);
    printf("%c\n", aLetter);
}
like image 34
abelenky Avatar answered Nov 01 '22 22:11

abelenky