取代C语言标准输入输出:cin 和 cout【C++标准输入输出】
生活随笔
收集整理的這篇文章主要介紹了
取代C语言标准输入输出:cin 和 cout【C++标准输入输出】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- C語言 和 C++ 標準輸入輸出的區別
- cin標準輸入
- 解決scanf輸入字符的問題
- 解決C語言輸入字符串的問題
- cout
- 進制輸出
- 域寬
- 左對齊 / 右對齊
- 填充
- 設置有效數字
- 設置浮點數精度
C語言 和 C++ 標準輸入輸出的區別
cin 取代 scanf
cout 取代 printf
scanf 和 printf 本質是函數。
cin 和 cout 本質是類對象。
cin標準輸入
代碼演示:
#include <iostream>int main() {int a, b, c;std::cin >> a >> b >> c;std::cout << "a = " << a << " b = " << b << " c = " << c << std::endl;return 0; }運行結果:
輸入間隔可以不限次使用:空格、Tab和回車,最后一個輸入后用回車表示輸入結束。
>> 表示流輸入運算符,也表示右移運算符,這種現象稱為運算符重載,重載運算符的作用:根據語境判斷。
<< 表示流輸出運算符。
解決scanf輸入字符的問題
char m; int n; scanf("%d%c", &n, &m);C語言解決方案:
C++解決方案:cin>>n>>m;
解決C語言輸入字符串的問題
char buf[10]; scanf("%s", buf); //C語言不安全的字符串輸入scanf 輸入字符串有空格時,會丟失空格之后的字符串。
char buf[10]; fgets(buf, 10, stdin); //C語言安全的字符串輸入 讀取前9個字符 + \0fgets 輸入字符串有空格時,不會丟失空格之后的字符串。
char buf[10]; cin >> buf; //C++不安全的輸入字符串cin 輸入 buf[10] 字符串有空格時,會丟失空格之后的字符串。
char buf[10]; cin.getline(buf, 10); //C++安全的輸入字符串 讀取前9個字符 + \0cin.getline();輸入字符串有空格時,不會丟失空格之后的字符串。
string str; cin >> str; //C++安全的字符串輸入cin 輸入 string 字符串有空格時會丟失空格之后的字符串。
cout
進制輸出
代碼演示:
#include <iostream>using namespace std;int main() {//進制輸出int data = 1234;cout << data << endl; //十進制輸出cout << hex << data << endl; //十六進制輸出 hex 表示流算子cout << oct << data << endl; //八進制輸出cout << dec << data << endl; //十進制輸出return 0; }運行結果:
域寬
代碼演示:
#include <iostream> #include <iomanip>using namespace std;int main() {//域寬float f = 1.234;cout << f << endl;cout << setw(10) << f << endl; //設置域寬為10return 0; }運行結果:
左對齊 / 右對齊
代碼演示:
#include <iostream> #include <iomanip>using namespace std;int main() {float f = 1.234;//左對齊 右對齊 默認情況右對齊cout << setw(10) << setiosflags(ios::left) << f << endl;cout << setw(10) << setiosflags(ios::right) << f << endl;return 0; }運行結果:
填充
代碼演示:
#include <iostream> #include <iomanip>using namespace std;int main() {//填充 默認填充空格int a = 12;int b = 2;int c = 5;//用字符 0 填充cout << setfill('0') << setw(2) << a << ":" << setw(2) << b << ":" << setw(2) << c << endl;return 0; }運行結果:
設置有效數字
代碼演示:
#include <iostream> #include <iomanip>using namespace std;int main() {//設置有效數字float ff = 1.23456;cout << setprecision(3) << ff << endl;return 0; }運行結果:
設置浮點數精度
代碼演示:
#include <iostream> #include <iomanip>using namespace std;int main() {//設置浮點數精度float ff = 1.23456;cout << setprecision(3) << setiosflags(ios::fixed) << ff << endl;return 0; }運行結果:
總結
以上是生活随笔為你收集整理的取代C语言标准输入输出:cin 和 cout【C++标准输入输出】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 想和高手侃侃而谈C++引用?看这一篇就够
- 下一篇: 类与面向对象的精华:继承【C++继承】