|
Use the following format with printf.
%s
Write a null-terminated string (without the null character).
For example, if s is a variable of type char*
and s points to string "camel", then
printf("My pet %s is named Flower\n", s);writes My pet camel is named Flower |
Use the following formats with scanf.
%s
Read a string. Statement
char s[100];
scanf("%s", s);
skips over white space (if any), then reads characters
up to a white space character or the end of the input,
storing the characters into array s. It adds
a null character to the end.
Warning. Do not write char* s = new char[100]; scanf("%s", &s);Format %s wants an array (a pointer to a chunk holding characters), not the address of a variable that holds an array. Warning. The %s format does not allocate memory. Statements
char* s;
scanf("%s", s);
fail to initialize s. That makes scanf store characters
at a memory address that is a
dangling pointer.
Warning. Reading strings using %s is dangerous. If the string in the input is too long, scanf will store characters outside of the array. See %ms. |
%ms
Read a string. Statement
char* s;
scanf("%ms", &s);
is similar to the same thing with %s, but %ms allocates
enough memory to hold the string that it reads, and
stores a pointer to the newly allocated array into s.
Notice that, in this case, you do want &s. The parameter
corresponding to %ms must have type char**.
The memory is allocated using malloc. To delete the array, use free(s); |
%m[A-za-z]
This is similar to %ms, but it omits skipping over initial white space
and reads a string consisting of zero or more letters. You can list
individual characters, as in [aeiou], and can give character ranges, such
as a-z. For example,
char* p;
scanf("%m[a-z]", &p);
reads a string of lower-case letters.
|
%m[^A-za-z]
The ^ character means anything except these. So you get a string of nonletters. |
|