scanf

'Never too more, but not less' principle: 

  If there are too many arguments for the given specifications, the extra arguments are evaluated but ignored. The results are unpredictable if there are not enough arguments for the format specification.

    int iVar0 = 0 ;
int iVar1 = 0 ;
char buf[1024] = {'\0'} ;

// %[*] [width] [{h | l | ll | I64 | L}]type

// If a percent sign (%) is followed by
// a character that has no meaning
// as a format-control character,
// that character and the following
// characters (up to the next percent sign)
// are treated as an ordinary sequence of characters,
// that is, a sequence of characters that must match the input.
// For example, to specify that a percent-sign character
// is to be input, use %%.
scanf("%d-%d", &iVar0, &iVar1) ; // You must input a '-' between two integers
printf("%d %d", iVar0, iVar1) ;

// An asterisk (*) following the percent sign suppresses
// assignment of the next input field,
// which is interpreted as a field of the specified type.
// The field is scanned but not stored.
scanf("%*d %d", &iVar0) ; // Ignore the first input field by '%*'
printf("%d %d\n", iVar0, iVar1) ;

// To store a string without storing a
// terminating null character ('\0'),
// use the specification %nc where n is a decimal integer.
// In this case, the c type character indicates
// that the argument is a pointer to a character array.
// The next n characters are read from the input stream into
// the specified location, and no null character ('\0') is appended.
// If n is not specified, its default value is 1.
scanf("%10c", buf) ; // <Enter> is considered as two characters.
printf(
"%s\n", buf) ;


// To read strings not delimited
// by whitespace characters,
// a set of characters in brackets ([ ])
// can be substituted for the s (string) type character.
// The set of characters in brackets
// is referred to as a control string.
// The corresponding input field is read up to
// the first character that does not appear in
// the control string. If the first character
// in the set is a caret (^), the effect is reversed:
// The input field is read up to the first character
// that does appear in the rest of the character set.
scanf("%[a-zA-Z 0-9]", buf) ; // The input will be treated as one string
// when the characters in '[]'
scanf("%[^\n]", buf) ; // The input will be treated as one string
// when the characters not in '[]'
printf("%s\n", buf) ;

  

posted @ 2011-08-06 18:11  walfud  阅读(338)  评论(0编辑  收藏  举报