Accelerated C++<3-4>

//编写一个程序用于报告它的输入中最长以及最短字符串的长度



Hint

For each word that is input, keep track of the shortest and longest words you’ve encountered.


Solution

Create two variables of type string::size_type: one to hold the shortest size, and one to hold the longest size. As the program proceeds through the input loop it first checks to see if shortest_size has been assigned a value other than zero. If not, it assigns it the first string’s size; otherwise it checks to see if the current string is shortest than shortest_size. It then checks to see if the current string is longer than longest_size.



#include<iostream>
#include<string>
using namespace std;


int main(){
//提示用户输入 
cout<<"please enter a few words,followed by end-of-file"<<endl;

string::size_type shortest_size=0;
string::size_type longest_size=0;

string word;
while(cin>>word)
{
//如果shortest_size值为0,则它还未被分配,,否则,看当前值是否更短,如果是,将当前值的尺寸赋给shortest_size 
if(shortest_size==0||word.size()<shortest_size)
shortest_size=word.size();

//看当前值长度是否比longest_size长,如果是,则将当前值长度赋给longest_size 
if(word.size()>longest_size)
longest_size=word.size();
}

//最后输出 
cout<<"The length of the shortest word is: "<<shortest_size<<endl
<<"The length of the longest word is: "<<longest_size<<endl;

return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值