Search

9/02/2006

scanf + size_t

int main()
{
char dummy[100];
char buf[100];
 
scanf("%s\n", dummy);
gets(buf);
 
printf("|%s|\n", buf);
}

input:
ABCDEF
123
output:
|123|
注意scanf會吃掉123前面的三個space
int main()
{
char dummy[100];
char buf[100];

scanf("%s", dummy);
gets(buf);
printf("|%s|\n", buf);
}

input:
ABCDEF
123
output:
||
注意scanf會吃掉空白但是不會吃掉'\n'

http://beej.us/guide/bgc/output/html/scanf.html
%[

This is about the weirdest format specifier there is. It allows you to specify a set of characters to be stored away (likely in an array of chars). Conversion stops when a character that is not in the set is matched.

For example, %[0-9] means "match all numbers zero through nine." And %[AD-G34] means "match A, D through G, 3, or 4".

Now, to convolute matters, you can tell scanf() to match characters that are not in the set by putting a caret (^) directly after the %[ and following it with the set, like this: %[^A-C], which means "match all characters that are not A through C."

To match a close square bracket, make it the first character in the set, like this: %[]A-C] or %[^]A-C]. (I added the "A-C" just so it was clear that the "]" was first in the set.)

To match a hyphen, make it the last character in the set: %[A-C-].

So if we wanted to match all letters except "%", "^", "]", "B", "C", "D", "E", and "-", we could use this format string: %[^]%^B-E-].

沒有留言: