Compare elements of the string.
Jan 16, 2018 at 10:03pm UTC
Good day,
I need to get several numbers from the user and compare it. If they are growth - print it to the screen. If decreasing - another output. In my code, I always get the same result "Decreasing!". I'm not sure is it valid to use such comparison in this situation
var1[i] < var1[i + 1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include <iostream>
#include <string>
using namespace std;
void compare(bool x)
{
if (x == true )
{
cout << "Increasing!" << endl;
}
else if (x == false )
{
cout << "Decreasing!" << endl;
}
}
int main()
{
string var1;
bool res1;
cout << "Please input numbers here:\t" ;
cin >> var1;
for (int i = 0; i != var1.length(); i++)
{
if (var1[i] < var1[i + 1])
{
res1 = true ;
}
else if (var1[i] > var1[i + 1])
{
res1 = false ;
}
}
compare(res1);
return 0;
}
Last edited on Jan 16, 2018 at 10:04pm UTC
Jan 16, 2018 at 10:27pm UTC
I need to get several numbers from the user and compare it.
If you're trying to input numbers why are you using a string for your user input? Wouldn't using a numeric type make more sense?
By the way what should happen if the two numbers are equal?
Also your function can be simplified:
1 2 3 4 5 6 7 8 9 10 11
void compare(bool x)
{
if (x)
{
cout << "Increasing!" << endl;
}
else
{
cout << "Decreasing!" << endl;
}
}
Topic archived. No new replies allowed.