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?
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";
}
}
if (tab[0][0] == std::to_string(1)) {....}because you cannot cast string to intif (tab[0] == std::to_string(1)) {....},tab[0][0]is a character.if (tab[0][0] == '1') {....}would be enough...