#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main () {
const int SZ = 5;
string word[SZ];
int len,min,large,max;
for(int i = 0; i < SZ; i ){
cout << "Please Enter a word five times: ";
cin >> word[i];
}
min = word[SZ].length();
for(int i = 0; i < SZ; i ){
if(word[i] < len){ // I'm getting it on this line of code
min = word[i];
}
}
return 0;
}
My code is not properly running and currently I'm trying to find the smallest word of 5 different words inputted by the user.
CodePudding user response:
There are some mitakes in your code:
Your first
cout
should be above thefor
loop rather than inside of it.word[SZ].length()
is accessing a string that is out of bounds of the array. You should be accessing the 1st string atword[0]
instead.on the statement
if(word[i] < len)
,len
is uninitialized. For that matter, you don't even needlen
at all, usemin
instead. But more importantly, you are comparing astring
to anint
, which is why you are getting an error. You need to compare the string'slength()
value instead.
Try this:
#include <iostream>
#include <string>
using namespace std;
int main () {
const int SZ = 5;
string word[SZ];
int min, max;
cout << "Please enter " << SZ << " words: ";
for(int i = 0; i < SZ; i ){
cin >> word[i];
}
min = max = word[0].length();
for(int i = 1; i < SZ; i ){
if (word[i].length() < min){
min = word[i].length();
}
if (word[i].length() > max){
max = word[i].length();
}
}
cout << "min: " << min << ", max: " << max << endl;
return 0;
}
CodePudding user response:
For starters, this (modified) statement:
cout << "Please Enter " << SZ << " words: ";
should be placed before the for
loop:
for(int i = 0; i < SZ; i ){
cin >> word[i];
}
In this statement:
min = word[SZ].length();
you are using a non-existent element of the array with the index SZ
, while the valid range of indices for the array is [0, SZ)
.
So, rewrite it like:
auto min = word[0].length();
Within the for
loop, this statement:
if(word[i] < len)
does not make sense. You need to write:
if(word[i].length() < min)
Also, this statement:
min = word[i];
has invalid operands for the assignment operator.
The loop can look like
auto min = word[0].length();
for( size_t i = 1; i < SZ; i ){
if( word[i].length() < min ){
min = word[i].length();
}
}
If you need to find the word with the minimal length then the for loop can look the following way
size_t min = 0;
for( size_t i = 1; i < SZ; i ){
if( word[i].length() < word[min].length() ){
min = i;
}
}
Pay attention to that, there is a standard algorithm std::min_element
declared in the header <algorithm>
that can be used instead of the manually written loop.