-3

I have this code which gets a string from the user, and it will find the digits and put them in a vector. Then it will find the highest number in the vector.

Question: How should I edit it so it would find if its even or odd?

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cctype>

using namespace std;

int main() {
    string str;
    getline(cin, str);
    vector<int> vec;
    for(int i = 0; i < str.length(); i++){
        if(isdigit(str[i])){
            vec.push_back(str[i]);
        }
    }
    int max = *max_element(vec.begin(), vec.end());
    if(max / 2 == 0){
        cout << "is even";
    } else {
        cout << "is odd";
    }
    return 0;
}

i want an output such as this:

input:

Hgj326nm2tgh21salamcup

output:

is even

or

input:

eMok2404fggh5987fgf52fgf21

output:

is odd
Casey
  • 10,297
  • 11
  • 59
  • 88
  • `(int)(vec[i]); // this will turn ascii numbers to an int, idk how` <-- that code doesn't do anything at all; the items in a `vector` were already ints, so casting one of them to int again is redundant, and in any case the result of the expression is discarded. – Jeremy Friesner Apr 29 '22 at 04:49
  • *"input: `Hgj326nm2tgh21salamcup`"* -- before testing complex cases, try a simple one. What should the output be for the input `2`? What is the actual output? What is the value of `max` in this case? – JaMiT Apr 29 '22 at 05:03
  • `max/2 == 0` does not test if the value of `max` is even or odd. It tests if `max/2` (with rounding toward zero) is equal to zero, which is not the same thing. You need to compute the *remainder* and test that. Also, the `*max_element(vec.begin(), vec.end())` in your code gives undefined behaviour if `vec` has no elements. – Peter Apr 29 '22 at 05:32

1 Answers1

2

how to know if a vector's highest number is even or odd

You should replace the statement vec.push_back(str[i]); with:

//-------------------vvvvv----->subtract '0'
vec.push_back(str[i] - '0');

Demo

Explanation

'0' is a character literal. Here both str[i] and '0' will be promoted to int. And the final result that is added(appended) into the vector will be the result of subtraction of those two promoted int values. Moreover, it is guaranteed by the C++ Standard (2.3 Character sets) that:

  1. ...In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

This means that the difference between the two will give us the number that the character str[i] represents.


Additionally there is no need for having the following statement:

(int)(vec[i]);//no need for this statement

Also note that if(max / 2 == 0) should be:

//-----v---------->note the modulus
if(max % 2 == 0)

Also refer to Why should I not #include <bits/stdc++.h>?

Jason
  • 36,170
  • 5
  • 26
  • 60