如何创建一个程序,让它从用户那里读取文本,然后输出最短和最长的单词以及这些单词包含多少字符?
到目前为止,我只能创建一个计算文本中单词数量的程序。
int count_words {};
string word;
cout << "Type a text:" << endl;
while (cin >> word)
{
count_words++;
}
cout << "The text contains " << count_words << " words." << endl;
循环可以被操纵以确定最短和最长的单词吗?
只需声明几个string
变量,然后在while
循环中,当word.size()
大于/小于这些变量的size()
时,您可以将word
分配给这些变量,例如:
size_t count_words = 0;
string word, longest_word, shortest_word;
cout << "Type a text:" << endl;
while (cin >> word)
{
++count_words;
if (word.size() > longest_word.size())
longest_word = word;
if (shortest_word.empty() || word.size() < shortest_word.size())
shortest_word = word;
}
cout << "The text contains " << count_words << " word(s)." << endl;
if (count_words > 0) {
cout << "The shortest word is " << shortest_word << "." << endl;
cout << "It has " << shortest_word.size() << " character(s)." << endl;
cout << "The longest word is " << longest_word << "." << endl;
cout << "It has " << longest_word.size() << " character(s)." << endl;
}
在线演示
或者:
string word;
cout << "Type a text:" << endl;
if (cin >> word) {
size_t count_words = 1;
string longest_word = word, shortest_word = word;
while (cin >> word) {
++count_words;
if (word.size() > longest_word.size())
longest_word = word;
if (word.size() < shortest_word.size())
shortest_word = word;
}
cout << "The text contains " << count_words << " word(s)." << endl;
cout << "The shortest word is " << shortest_word << "." << endl;
cout << "It has " << shortest_word.size() << " character(s)." << endl;
cout << "The longest word is " << longest_word << "." << endl;
cout << "It has " << longest_word.size() << " character(s)." << endl;
}
else {
cout << "No text was entered." << endl;
}
在线演示