【C++】输出流cout方法

write():

输出指定字数的字符串。

basic_ostream<charT,traints>& write(const char_type* s, streamsize n);
1、write遇到空字符时不会停止
2、即使超出边界,write仍继续打印
3、可用于数据数据——需将数值数据强制转换为char*
#include <iostream>
#include <cstring>  // or else string.h

int main()
{
    using std::cout;
    using std::endl;
    const char * state1 = "Florida";
    const char * state2 = "Kansas";
    const char * state3 = "Euphoria";
	int len = std::strlen(state2);
    cout << "Increasing loop index:\n";
    int i;
    for (i = 1; i <= len; i++)
    {
        cout.write(state2,i);
        cout << endl;
    }
    cout << "Decreasing loop index:\n";
    for (i = len; i > 0; i--)
        cout.write(state2,i) << endl;
    cout << "Exceeding string length:\n";
    cout.write(state2, len + 5) << endl;
	long val=560031841;
	cout.write((char*)&val,sizeof(long));
	cout<<endl;
    return 0; 
}

dec()、hex()、oct()

计数制函数:十进制、十六进制、八进制
    cout << "Enter an integer: ";
	int n;
	cin >> n;
    cout << "n     n*n\n";
    cout << n << "     " << n * n << " (decimal)\n";
 // set to hex mode
    cout << hex;
    cout << n << "     ";
    cout << n * n << " (hexadecimal)\n";
 // set to octal mode
    cout << oct << n << "     " << n * n << " (octal)\n";
 // alternative way to call a manipulator
    dec(cout);
    cout << n << "     " << n * n << " (decimal)\n";


width()、fill():

调整字宽、填充字符
int main()
{
    using std::cout;
    int w = cout.width(30);
    cout << "default field width = " << w << ":\n";
    cout.width(5);
    cout << "N" <<':';
    cout.width(8);
    cout << "N * N" << ":\n";
    for (long i = 1; i <= 100; i *= 10)
    {
        cout.width(5);
        cout << i <<':';
        cout.width(8);
        cout << i * i << ":\n";
    }
	cout.fill('*');
	const char * staff[2] = { "Waldo Whipsnade", "Wilmarie Wooper"};
	long bonus[2] = {900, 1350};

	for (int i = 0; i < 2; i++)
	{
		cout << staff[i] << ": $";
		cout.width(7);
		cout << bonus[i] << "\n";
	}
    return 0; 
}


iomanip设置格式

iomanip中3个常用的控制符:setprecision()、setfill()、setw(),分别用于设置精度、填充字符、和字段宽。
    // use new standard manipulators
    cout << showpoint << fixed << right;
    // use iomanip manipulators
    cout << setw(6) << "N" << setw(14) << "square root"
         << setw(15) << "fourth root\n";
    double root;
    for (int n = 10; n <=100; n += 10)
    {
        root = sqrt(double(n));
        cout << setw(6) << setfill('.') << n << setfill(' ')
               << setw(12) << setprecision(3) << root
               << setw(14) << setprecision(4) << sqrt(root)
               << endl;
   }


参见《输入流cin方法

*参考资料:《C++ Primer Plus 5nd》

(转载请注明作者和出处:http://blog.csdn.net/xiaowei_cqu 未经允许请勿用于商业用途)


猜你喜欢

转载自751401909.iteye.com/blog/1751777
今日推荐