c++ scanf函数

官方介绍 http://www.cplusplus.com/reference/cstdio/scanf/

C string that contains a sequence of characters that control how characters extracted from the stream are treated:

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters – see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments.

上面这段话讲的都是format specifier(格式说明符)的内容。有三点:

  1. 遇到空白字符:会忽略说明符开始的空格直到遇到第一个非空格;在说明符里面的单个空格表示匹配0个到无数个空格。
    int main(){
        char a='a';
        char b='b';
        scanf("        %c%c",&a,&b);
        //scanf("        %c %c",&a,&b);
        cout<<a<<(int)a<<endl;
        cout<<b<<(int)b<<endl;
    }
    /*第一种我们输入ac会返回ac,输入a空格返回a空格,输入a换行返回a换行
      第二种我们输入ac也会返回ac,输入a空格或者a换行,会提示我们继续输入,因为这些空白字符
      被说明符里面的空格所匹配了。
    
      所以标记符前面的空白被忽略,中间的连续空白都只起到一个作用,就是匹配输入流中的空白
    */
    
  2. 遇到非空白字符:必须在输入流中匹配它,否则返回。
  3. 格式标识符:这个就不说了,有一个需要注意,%d匹配0-9的所有数,类似00023这种能够读取,结果就是23。

你可能感兴趣的:(c++)