菜鸟笔记-从键盘输入一行文本,将输入文本的单词和对应单词长度输入到数组中,并输出

有待改进,输出没有对齐

#include<iostream>
#include<iomanip>
#include<sstream>
#include<string>

using namespace std;
int test(int a[],char b[][20],int num){//二维数组做形参,第二维必须标明 
	char ch;
	int i=0,j=0;
	while(1){
		ch=cin.get();
		if(ch=='\n'){
				num++;
				a[i]=j;
				break;
		}
				
		if(ch!=' '){
			b[i][j]=ch;
			j++;
		}
		else{
			a[i]=j;
			j=0;
			i++;
			num++;
		}
	}
	return num;
}

int main()
{	
	int a[20],num=0;//a[20]放单词长度 
	char b[100][20];//b[][]放单词 
	cout<<"输入一个英文句子:";
	
	num=test(a,b,num);
		
	 
	for(int k=0;k<num;k++){
		for(int l=0;l<a[k];l++)
			cout<<b[k][l];
		cout<<setiosflags(ios_base::right)<<setw(12)<<a[k]<<endl;
	}
	
	return 0;
}

 

string类大法好

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main(){
	string s;
	getline(cin,s);
	string word;
	while(s.find(" ")!=s.npos){
		word=s.substr(0,s.find(" "));
		s.erase(0,s.find(" ")+1);
		cout<<left<<setw(12)<<word<<left<<setw(8)<<word.length()<<endl;
	}
	cout<<left<<setw(12)<<s<<left<<setw(8)<<s.length()<<endl;
	
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值