scanf()函數中%[]格式控制符用法
作者:武漢華嵌-嵌入式培訓中心 助理講師 張老師
此格式控制符的基本格式爲:%[scanfset]
scanfset 有兩種形式:一種是以非 “^” 字符開頭的 scanset , 表示在讀入字符串時將匹配所有在 scanfset 中出現的字符,遇到非scanfset 中的字符時輸入就結束;另外一種形式是以 “^” 字符開頭的scanfset ,表示在讀入字符串時將匹配所有不在scanfset 中出現的字符,遇到scanfset 中的字符輸入就結束。
測試代碼 1 :
#include
int main()
{
char str[40] = { 0 } ;
scanf( “%[^\n]” , str ) ; //遇到回車鍵時字符串輸入結束
printf( “%s\n“ , str ) ;
return 0 ;
}
輸入 :hhhh &&&ni
Vc6.0的輸出結果:
Ubuntu10.04的輸出結果:
hhhh &&&ni
“-”字符的使用。當“-”出現在scanfset中且兩邊都有字符時,大多數編譯器都做了如下所述實現:“-”表示匹配從其左邊的字符到右邊字符之間所有的字符(按ASCII碼排序)。如a-z表示a到z的所有字符,又如0-9表示0到9這十個數字。所以,當scanfset爲0-9時表示只匹配數字串,當scanfset爲A-Za-z時表示只匹配字符(包括大小寫),當scanfset爲^0-9時不匹配所有數字。注意,“-”的字符只有在其左右兩邊都有有效字符時纔有這個作用,否則被認爲是普通字符,如“ 0-4-6-9”匹配的字符爲{0,1,2 ,3,,4, -, 6,7,8,9},這樣也爲輸入“-”字符提供了方法。
測試代碼 2 :
#include
int main()
{
char str[40] = { 0 } ;
scanf( “%[a-c-2-7-A-Z]” , str ) ;//遇到不是方括號中的字符輸入就結束,注意字符 “-”
printf( “%s\n“ , str ) ;
return 0 ;
}
輸入:b35U-
Vc6.0輸出結果:
Ubuntu10.04輸出結果:
b35U-
注意:
當要匹配右側 “]” 或者 “^” 時,得這樣去做。如果是右側方括號時,得把它放在緊跟在左側方括號的後邊,也不可以有空格,如:%[]ajdfidfj ] ;如果是 “^” 時,得不可以把它置於緊跟在左側方括號的後邊,如:%[ gfadhfu^fhgiu ] 。
測試代碼 3 :
#include
int main()
{
char str[40] = { 0 } ;
scanf( “%[ni^hao^ma]” , str ) ;//遇到不是方括號中的字符輸入就結束,注意字符 “^”
printf( “%s\n“ , str ) ;
return 0 ;
}
輸入:hao^
Vc6.0輸出結果:
Ubuntu10.04輸出結果:
hao^
測試代碼 4 :
#include
int main()
{
char str[40] = { 0 } ;
scanf(“%[]ni^hao^ma]”,str) ;//遇到不是方括號中的字符輸入就結束,注意字符 “]” printf( “%s\n“,str) ;
return 0 ;
}
輸入:hao]^
Vc6.0輸出結果:
Ubuntu10.04輸出結果:
hao]^
測試代碼 5 :
#include
void put()
{
char str1[40] = {0};
scanf("%[]nihao]",str1);
printf("%s\n\n",str1);
}
int main()
{
char str1[40] = {0};
char str2[40] = {0};
scanf("%[ni^hao^ma]",str1);
printf("%s\n\n",str1);
// fflush(stdin); 刷新鍵盤緩衝區的作用,但在ubunt10.04上面不起作用
// getchar(); 在vc6.0和ubuntu10.04上都起作用,接收一個字符,即爲鍵盤緩衝區的 \r ,也就是回車。
scanf("%[]nihao]",str2);
printf("%s\n\n",str2);
// fflush(stdin);
// getchar();
put();
return 0;
}
輸入:nihao^ 然後按回車鍵,整個程序就結束了。
輸出:
Vc6.0的輸出結果
Ubuntu10.04輸出的結果:
nihao^
nihao^
在vc6.0中,當去掉fflush()或者 getchar()的註釋時:
結果:
nihao^
nihao^
在ubuntu10.04中,當去掉getchar()的註釋時:
結果:
hao^
hao^
hao]
hao]
hao^
hao
(原文出處:武漢華嵌 http://www.embedhq.org/, 轉載請註明出處)