c++ --> cin和cout输入输出格式

时间:2022-04-04 23:13:14

cin和cout输入输出格式

Cout 输出

    1>. bool型输出

cout << true <<" or " << false <<endl ;              // 1 or 0
cout << boolalpha << true << " or " << false <<endl ; // true or false
cout << noboolalpha << true <<" or " <<false <<endl ; // 1 or 0
cout << boolalpha << 0 <<endl ; // 0 原因: 0 在cout中不等价于 false

    2>. 整型输出

const int ival =  ;        // 'ival' is constant, so value never change
cout << oct << ival <<endl ; // 21 8 进制
cout << dec << ival <<endl ; // 017 10 进制
cout << hex << ival <<endl ; // 0x11 16 进制
cout << hex << 17.01 <<endl ; // 17.01 : 不受影响 cout << showbase << uppercase ; // Show base when printing integral values
cout << hex << <<endl ; // 0XF 大写形式 cout << nouppercase ;
cout << hex << <<endl ; // 0xf 小写形式
cout << noshowbase ; // Reset state of the stream

    3>. 浮点型输出

cout << setprecision(4) << 12.345678 << endl ;    // 12.35  四舍五入(rounded)
cout << setprecision(10) << 12.345678 << endl ; // 12.345678
cout << cout.precision() << endl ; // 10 输出当前精度 cout << showpoint << 10.0 << endl ; // 10.0000
cout << noshowpoint << endl ; // 恢复默认状态

    4>. 科学计数法(scientific) 和 定点小数(fixed)

float f =  / 6.0 ;
cout << fixed << f <<endl ; // 16.83334 : 小数点后共6位
cout << scientific << f <<endl ; // 1.683333e+001 : 小数点后共6位
cout.unsetf(ostream::floatfield) ; // 恢复到初始状态

    5>. 输出填充

//输出宽度,只控制最近的一个输出
cout << setw() << 12.3 << endl ; // ______12.3 补齐10位
cout << setw() << << "###" << endl ; // ________12### //左对齐
cout << left ; // 左对齐
cout << setw() << << setw() << << endl ; // 12___34___ //补充指定字符
cout << setfill('*') ; // 补充 "*" 号
cout << setw() << << endl ; // 12*** //默认
cout << internal ; // 默认
cout << setw() << - <<endl ; // -**12

Cin 输入 

   1>. cin

输入结束条件 :遇到Enter、Space、Tab键。

int a;
cin >> a;

带符号输入,比如输入(a,b,c)

int a, b,;
cin >> a;
cin.ignore( , ',' );
cin >> b;

    2>. cin.get(数组名,长度,结束符)

其中结束符为可选参数,读入的字符个数最多为(长度-1)个,结束符规定结束字符串读取的字符,默认为ENTER,ch=cin.get() 与 cin.get(ch)等价。

//输入  "asdfqwert"
cin.get( c1, , 'q' ); //"asdf" 遇到‘q’结束,最多读取7个字符!!!
cin.get(c2); //获取字符 “q”
cin.clear();
cout << c1 << " " << c2 << endl; // “a s”打印两个字符
cout << ( int )c2 << endl; //

    3>. cin.getline()

cin.getline()当输入超长时,会引起cin函数的错误,后面的cin操作将不再执行。

//输入 “12345”
cin.getline(a, ); //“1234” 读取4个字符
cin >> ch; //“0”
cout << a << endl;
cout << (int)ch << endl;

这里其实cin>>ch语句没有执行,是因为cin出错了!