0
int main() {
    vector<string> tab;
    tab.push_back("1234");
    cout << tab[0][0];// -> 1
    if (int(tab[0][0]) == 1) {
        cout << "test";
    }
}

why does this comparison not work? what am I doing wrong?

3
  • You can use if (tab[0][0] == std::to_string(1)) {....} because you cannot cast string to int Commented Apr 1, 2020 at 7:14
  • @NutCracker You mean if (tab[0] == std::to_string(1)) {....}, tab[0][0] is a character. Commented Apr 1, 2020 at 7:18
  • @john actually if (tab[0][0] == '1') {....} would be enough... Commented Apr 1, 2020 at 7:20

4 Answers 4

2

'1' the character is not the same as 1 the integer.

To do your comparison write

if (tab[0][0] == '1') {

Specifically when you convert a character to an integer what you get is the encoding of the character. If you are using ASCII (which is very likely) then the encoding of '1' is 49.

Sign up to request clarification or add additional context in comments.

Comments

0

You're confusing numbers (1, 2, 3, ...) and digits ('1', '2', '3', ...).

They look the same when you print them, but they are not the same.

Comments

0

The expression tab[0][0] will evaluate to the first character of the first string in the tab vector. Note that this is a character representation (probably ASCII, but not necessarily so), which will not have the numerical value of 1 (it will have the value 49 if your system uses ASCII).

So, in your if test, you need to compare the value with a character literal rather than an integer literal, like so:

int main() {
    vector<std::string> tab;
    tab.push_back("1234");
    std::cout << tab[0][0];// -> 1
    if (int(tab[0][0]) == '1') { // Compare to the character '1'!
        std::cout << "test";
    }
}

Comments

0

If You Want To Convert A String To A Number Use The Function Atoi()

std::string str = "12345";
int num = std::atoi(str.c_str());
// num = 12345

If You Want one Single Character Not a char*

std::string str = "12345";
int num = str[0] - '0';
// num = 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.