使用scanf和printf函数 在C++程序中使用scanf 和printf需要“cstdio”头文件. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 #include <bits/stdc++.h> using namespace std ;int main () { int T; scanf ("%d" ,&T); printf ("%d" ,T); return 0 ; } #include <bits/stdc++.h> using namespace std ;int main () { double T; scanf ("%lf" ,&T); printf ("%lf" ,T); return 0 ; } #include <bits/stdc++.h> using namespace std ;int main () { int year; int month; int day; printf ("请输入需要转换的日期:" ); scanf ("%d/%d/%d" , &year, &month, &day); printf ("转换后的日期格式为:%d/%d/%d \n" , year, month, day); } #include <bits/stdc++.h> using namespace std ;int main () { string a; a.resize(100 ); scanf ("%s" ,&a[0 ]); printf ("%s" ,a.c_str()); }
使用cin 和 cout 函数
C++中可以使用流简化输入输出操作。
标准输入输出流在头文件iostream中定义,存在于名称空间std中。如果使用了using namespace std语句,则可以直接使用。
cin可以连续从键盘读取想要的数据,以空格、tab或换行作为分隔符1 2 3 4 5 6 7 8 9 10 11 #include <bits/stdc++.h> using namespace std ;int main () { string a,b; cin >>a>>b; cout <<a<<" " <<b<<endl ; } 程序输入"Hello World" ,将会在下一行输出"Hello World" ; 其中输入的"Hello" 赋值给a,"World" 赋值给b,中间的空格就是分隔符。
虽然使用cin很方便,但是它比scanf慢。在某些题上,可能会因为这个cin而吃亏。
解决方法:1 2 ios::sync_with_stdio(false );
此时的cin就会比scanf快,那么请问还有没有更快的呢? 答案是肯定的! 在看题解的时候,我看见有大佬是这样写的:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <bits/stdc++.h> using namespace std ;inline int read () { char c = getchar(); int x = 0 , f = 1 ; while (c < '0' || c > '9' ) {if (c == '-' ) f = -1 ; c = getchar();} while (c >= '0' && c <= '9' ) x = x * 10 + c - '0' , c = getchar(); return x * f; } int main () { int a,b; a=read(); b=read(); cout <<a<<" " <<b<<endl ; }
输入速度大致:read() < 加了ios::sync_with_stdio(false)的cin < scanf() < cin ;
使用文件输入输出 先说个最简单的吧—重定向 1 2 3 freopen("data.in" ,"r" ,stdin ); freopen("data.out" ,"w" ,stdout );
1 2 3 4 5 6 7 8 9 10 11 12 13 #include <bits/stdc++.h> using namespace std ;int main () { freopen("data.in" ,"r" ,stdin ); freopen("data.out" ,"w" ,stdout ); int a,b; scanf ("%d%d" ,&a,&b); printf ("%d %d" ,a,b); return 0 ; }
如果比赛要求用文件输入输出,但是禁止用重定向的方式————fopen 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <bits/stdc++.h> using namespace std ;int main () { FILE*fin,*fout; fin=fopen("data.in" ,"rb" ); fout=fopen("data.out" ,"wb" ); int a,b; fscanf (fin,"%d%d" ,&a,&b); fprintf (fout,"%d %d" ,a,b); fclose(fin); fclose(fout); return 0 ; }
重定向的方法写起来简单,但是不能同时读写文件和标准输入输出;
fopen写法比较繁琐,但可以改成读写标准输入输出,只需"fin=stdin;fout=stdout;",不调用fopen和fclose;
计时函数clock() 1 2 3 4 #include <time.h> int main () { printf ("Time used=%.2f\n" ,(double )clock()/CLOCKS_PER_SEC); }