Longest and Shortest String
So, for this exercise I am suppose to take in an input and output the longest and shortest string. This exercise does not seem hard at all but for some reason my code only outputs the longest string, and not the shortest. It just leaves it as blank.
Example:
input: a b c d e longesttt ggg
output: Shortest: a
Longest: longesttt
Code:
#include <iostream>
#include <string>
#include <vector>
#include <conio.h>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
int main(){
//asks for list of words
cout << "Please give me a list of words:" << endl;
string x;
vector<string> words;
//adds the input to the vector
while (cin >> x){
words.push_back(x);
}
//checks to see if user inputted anything
if (words.size() == 0){
cout << "I didn't receive any input." << endl;
cout << "Press any key to continue...";
_getch();
return 1;
}
//the containers
string longest;
string shortest;
//checks for the shortest and longest string
for(int i = 0; i != words.size(); i++){
if(words[i].length() < shortest.length()){
shortest = words[i];
}
if(words[i].length() > longest.length()){
longest = words[i];
}
}
//the output
cout << "Shortest: " << shortest << endl;
cout << "Longest: " << longest << endl;
cout << "Press enter to continue...";
_getch();
return 0;
}
Thank you for your help!!