不過 cout 的速度會比 printf 慢
至於是不是慢許多
其實也還好
在 C++ 中
也多了一種 data type 可以用
就是 string
比在 C 時只能宣告字元陣列方便許多
不過
就是有人想要 printf 的快速(?) 跟 string 的方便
就來以幾行程式來作範例
註解都有就自行查看囉OuO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<cstdio> | |
#include<string.h> | |
using namespace std; | |
int main() | |
{ | |
char str1[10]; //C的字元陣列 | |
strcpy(str1, "abc"); //只能以str的操作來賦值:麻煩=''= | |
printf("%s\n", str1); //printf輸出:快 | |
cout << str1 << endl; //cout輸出:慢 | |
string str2; //C++的string | |
str2 = "def"; //可直接用=賦值:方便OuO | |
cout << str2 << endl; //cout輸出:慢 | |
printf("%s\n", str2.c_str());//printf輸出:快 | |
//注意使用.c_str() | |
return 0; | |
} |
Compilation : g++ -o pricin pricin.cpp
Execution : ./pricin
參考資料:神人老師!!!!
105.07.10
針對 cin/cout 和 scanf/printf 有補充資料
C++的輸出入cin/cout和scanf/printf誰比較快?