Smartyguy1
Smartyguy1

Reputation: 13

I am having some trouble with if function with char

Here, When I input CO2, it is processing the 'else' statement and if I input anything else it is still the same

I tried changing 'co2' to "co2" but then it doesn't even work

int main(int nNumberofArgs, char* pszArgs)
{
    char symb[5];

    cout << "Enter Symbol: ";
    cin >> symb[5];

    if (symb[5] == 'co2')
    {
        cout << "This is Carbon-Dioxide" << endl;
    }
    else
    {
        cout << "Error" << endl;
    }

    return 0;
}

Upvotes: 0

Views: 53

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598134

Your code is written all wrong.

The statement char symb[5]; declares a fixed sized array that can hold 5 char elements max. But when you do cin >> symb[5];, you are not reading up to 5 chars into the array, you are reading a single char into the 6th slot of the array, corrupting surrounding memory.

Also, symb[5] == 'co2' is not the right way to compare the contents of the array. You are comparing the 6th (invalid) char against a single multi-byte character, you are not comparing the whole content of the array against a multi-character string.

Try something more like this instead:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char symb[5];

    cout << "Enter Symbol: ";
    cin.get(symb, 5);

    if (strcmp(symb, "co2") == 0)
    {
        cout << "This is Carbon-Dioxide" << endl;
    }
    else
    {
        cout << "Error" << endl;
    }

    return 0;
}

That being said, using a std::string instead of a char[] is better:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string symb;

    cout << "Enter Symbol: ";
    cin >> symb;

    if (symb == "co2")
    {
        cout << "This is Carbon-Dioxide" << endl;
    }
    else
    {
        cout << "Error" << endl;
    }

    return 0;
}

Upvotes: 1

Related Questions