Home > front end >  Determine the longest word in a text input
Determine the longest word in a text input

Time:12-01

How do I create a program where it reads in text from the user and then outputs the shortest and longest words and how many characters these words contain?

So far, I can only create a program that counts the number of words in the text.

int count_words {};
string word;

cout << "Type a text:" << endl;

while (cin >> word)
{
    count_words  ;
}
    
cout << "The text contains " << count_words << " words." << endl;

Can the loop be manipulated so that it determines the shortest and longest words?

CodePudding user response:

Simply declare a couple of string variables, and then inside the while loop you can assign word to those variables when word.size() is larger/smaller than the size() of those variable, eg:

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

Online Demo

Alternatively:

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

Online Demo

  •  Tags:  
  • c
  • Related