02. cout的格式化输出
1.输出进制
cout.setf(std::ios_base::dec);//设为十进制 cout << 16 << endl;//打印十进制16 cout.setf(std::ios_base::hex);//设为十六进制 cout << 16 << endl;//打印10,没有0x前缀 cout.setf(std::ios_base::oct);//设为八进制 cout << 16 << endl;//打印20,没有0前缀 cout.unsetf(std::ios_base::oct);//使指定标志位关闭 cout << 16 << endl;//打印十进制16 cout << std::hex << 16 << endl//std::hex内部调用setf << std::oct << 16 << endl << std::dec << 16 << endl; cout << std::showbase //std::showbase内部调用setf(ios_base::showbase) << std::hex << 16 << endl//打印0x10 << std::oct << 16 << endl//打印020 << std::dec << 16 << endl;//打印16 cout << std::hex << std::uppercase//浮点和十六进制整数的输出中使用大写 << 169 << endl//0XA9 << 179 << endl//0XB3 << 189 << endl//0XBD << std::scientific << 123.456 << endl//1.234560E+02 << 567.123 << endl;//1.234560E+02
2.科学记数法
cout.setf(std::ios_base::scientific, std::ios_base::floatfield);//设置flag cout << 2345.678 << endl;//2.345678e+03 cout.unsetf(std::ios_base::scientific);//取消flag cout << 2345.678 << endl;//2345.68 cout << std::scientific //std::scientific内部调用setf << 2345.678 << endl;//2.345678e+03 cout.setf(std::ios_base::fixed, std::ios_base::floatfield);//设置flag cout << 2345.678 << endl;//2345.68 cout << std::fixed << 2345.678 << endl;//std::fixed内部调用setf
3.设置精度
cout.precision(6);//设置精度为3 cout << 2345.678 << endl;//2345.68
4.设置对齐
cout.width(10); cout.fill('$');//设置填充字符,默认为空格 cout << std::right << "Hello" << endl;//打印$$$$$Hello cout.width(10);//再调用一次 cout << std::left << "Hello" << endl;//Hello$$$$$
5.cin的用法
char name[100] = {}; int age = 0; //符合预期的情况 cin >> name >> age;//假设输入一行,内容为:Jack 19 cout << name << " " << age << endl;//输出为:Jack 19 //不符合预期的情况,空白,回车,tab都会截断 cin >> name >> age;//假设输入一行,内容为:Jack Joe 19 cout << name << " " << age;//输出为:Jack 0 //清掉cin缓冲区里的数据 long long count = cin.rdbuf()->in_avail(); cin.ignore(count); //读取一行,包括空格和tab cin.getline(name, sizeof(name)); cout << name;