cin.width() & cout.width()

匿名 (未验证) 提交于 2019-12-02 23:26:52

1. cin.width(n);

会把字符串全部读取,分成几块,每块n-1个字符,只输出第一块,如果字符串长度不满 n-1,剩下的用空格补齐;

从第n个字符开始到字符串不输出,输出时n-1个字符前边没有空格;同样也是只输出第一块

 #include <iostream>  using namespace std;   int main(){        int width = 4;        char str[20];          cout << "请输入一段文本: \n";         cin.width(5);	//cin>>str;实际只能提取4个字符,str最后一个是空字符,其他的放在流中等待接受。           while( cin >> str )      {               // cout.width(width++);	//将4个字符输出,设置每次输出的域宽增加1     //cin >> str;               cout << str << endl;	//输出str                cin.width(5);			//设置接受4个字符           }          return 0;} 

结果:

2. cout.width(n);

输出n个字符,字符自动右对齐,左边用空格补上,视字符串中的空格为读取断开,即遇到空格时认为读取完了一块,在读取下一块,如果字符串长度大于n,则全部读取到下一个空格读完一块;

 #include <iostream>  using namespace std;   int main(){        int width = 4;        char str[20];          cout << "请输入一段文本: \n";        //cin.width(5);	//cin>>str;实际只能提取4个字符,str最后一个是空字符,其他的放在流中等待接受。           while( cin >> str )      {               cout.width(width);	//将4个字符输出,设置每次输出的域宽增加1     //cin >> str;               cout << str << endl;	//输出str                //cin.width(5);			//设置接受4个字符           }          return 0;} 

结果:

文章来源: https://blog.csdn.net/qq_41867007/article/details/88747843
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!