C++ 輸入輸出
阿新 • • 發佈:2020-12-19
C++ i/o
C++的發展(c plus plus)
1) 對C的語法做了擴充套件
2) 面向物件程式設計(思想)
3)C++版本
98 03 11 14 17 20 23
相關網站: isocpp.org
zh.cppreference.com
工具:vs2019
c++對C的提升
型別敏感:
int n = 8;
int n1 = 5.6;
int n2 = 3.4f;
//int n3 = { 5.6 };
//int n3 = { 5 };
//char ch = { 0x8755 };
使用{}賦值,型別嚴格匹配
型別佔位符:
//型別佔位符,型別推到符,根據=右側的值推匯出左側變數的型別 int n = 9; auto n0 = 3;//3是int型別,所以推匯出no是int型別 auto p = "test"; auto f = 3.6f; //p=55;//報錯,p是const char*型別,不能賦值int型別的值 //auto z;//報錯,沒有值可以用於推到Z的型別 decltype(p) p1 = "world";//使用p的型別推導p1的型別 decltype(p) p2; //p2=5;//報錯,根據p的型別推導到p2的型別為 const char*,所以不能賦值int型別的值 //型別比較複雜的時候 char************* ary[12]; decltype(ary[0]) nData = ary[1];
空指標:
char* p = NULL;//巨集
int n = NULL;//可讀性差,第一眼看過去,以為n是指標型別
char* p1 = nullptr;//關鍵字
//int n = nullptr;//報錯,nullptr只能用於指標型別。
範圍迭代
//範圍迭代 int ary[] = { 12,5,6,7,8,21,174,2,4,872,7 }; for (int i = 0; i < sizeof(ary) / sizeof(ary[0]); i++) { printf("%d", ary[i]); } printf("\r\n"); for (int val : ary) printf("%d", val); printf("\r\n");
輸出
std::cout 定義標頭檔案
萬物皆可 hello world
std::cout << "hello world" << std::endl;//作用域運算子,end1相當於\r\n
std::cout << 5 << std::endl;
std::cout << 5.3f << std::endl;
std::cout << 6.3 << std::endl;
可以全域性定義 using namespace std;//名稱空間
可以省去cout前面的std::
cout << "hello world" << std::endl;//作用域運算子,end1相當於\r\n cout << 5 << std::endl; cout << 5.3f << std::endl; cout << 6.3 << std::endl;
可以再省略一點
cout << "hello world" << " "
<< 5 << " "
<< 5.3f << " "
<< 6.3 << " "
<< std::endl;
進位制
cout預設輸出十進位制
呼叫setf()
cout.setf(ios_base::hex, ios_base::basefield);
cout << 0x213 << std::endl;
cout.setf(ios_base::oct, ios_base::basefield);
cout << 1234 << std::endl;
cout.setf(ios_base::dec, ios_base::basefield);
cout << 133 << std::endl;
計數方式
cout << std::fixed << 13.5687 << endl;
cout << std::scientific << 13.54896 << endl;
cout << std::scientific << -13.54896 << endl;
cout.precision(3);
cout << std::fixed << 13.5687 << endl;
cout << std::scientific << 13.5687 << endl;
cout.unsetf(ios_base::scientific);//取消科學計數法,恢復預設的定點法
cout.precision(4);
cout << 536.78545665 << std::endl;
對齊
顯示字首 showbase
顯示(不顯示)浮點數的點showpoint & noshowpoint
剩下功能如上圖。
注意:std::uppercase用於字元中沒效果,要用於十六進位制的字元大小寫。
輸入
cin的一般使用
int n;
float f;
double dbl;
char szBuff[255] = { 0 };
cin >> n >> f >> dbl >> szBuff;
在控制檯中直接輸入資料。
cin>>szBuff>>n;//輸入hello world 22,會出錯,空格截斷導致後面的輸入出錯
應該新建緩衝區,讀取大小直接丟掉。
int n;
char szBuff[255] = { 0 };
cin >> szBuff;
int nCntAvail = cin.rdbuf()->in_avail();
cin.ignore(nCntAvail);//從緩衝區讀取大小,再ignore
cin >> n;
如果想要把空格也一起讀取。可以使用 cin.getline
char arr[255]={0};
cin.getline(ary,sizeof(ary))//讀一行