cin.width() & cout.width()

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;}

结果:

 

 

 

 

 

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值