// crt_scanf_s.c // This program uses the scanf_s and wscanf_s functions // to read formatted input. #include <stdio.h> int main( void ) { int i, result; float fp; char c, s[81]; wchar_t wc, ws[81]; result = scanf_s( "%d %f %c %C %s %S", &i, &fp, &c, 1, &wc, 1, s, 80, ws, 80 ); printf( "The number of fields input is %d/n", result ); printf( "The contents are: %d %f %c %C %s %S/n", i, fp, c, wc, s, ws); result = wscanf_s( L"%d %f %hc %lc %S %ls", &i, &fp, &c, 2, &wc, 1, s, 80, ws, 80 ); wprintf( L"The number of fields input is %d/n", result ); wprintf( L"The contents are: %d %f %C %c %hs %s/n", i, fp, c, wc, s, ws); }
用scanf_s获取字符串时,要指定大小。
又例:
/* *文件名称:sub2.cpp *文件标识: *摘 要:C语言课本习题10.2:输入3个字符串,按由大到小的顺序输出。 * *当前版本:1.0 *作 者:徐峰 *完成日期:2011.2.16 * *取代版本: *原 作 者: *修 改: */ #include<stdio.h> #include<string.h> #define N 3 #define MAX 10 void main() { void sort(char *chr[],int m); char name[N][MAX]; char *name_addr[N]; int i; for(i=0;i<N;i++) { scanf_s("%s",name+i,MAX);//MAX为指定的大小 name_addr[i]=name[i]; } sort(name_addr,N); for(i=0;i<N;i++) { printf("/n"); printf("%s",name_addr[i]); } } void sort(char *chr[],int m) { int i,j; char *temp; for(i=0;i<m-1;i++) { for(j=i+1;j<m;j++) { if(strcmp(chr[i],chr[j])>0)//if(strcmp(name[i],name[j])>0) { temp=chr[i]; chr[i]=chr[j]; chr[j]=temp; } } } }
