//编写一个程序用于报告它的输入中最长以及最短字符串的长度
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;
}