简体   繁体   中英

My if-else statement does not work, does anyone know how to fix it?

Basically, I have a project due in about 2 days, and I cannot find how to make this if else statement work. I've done it before. I do not know what I am doing wrong.

#include <iostream>
using namespace std;

int main()
{
    int response;
    cout << "is your circuit a parallel circuit?";

    if (response == 'Y')
    {
        cout << "yes";
    }
    else (response == 'N')
    {
        cout << "no";
    }
    return 0;
}

I do not know what this means:

图片

int response;

If you want to read a character, response should be a char not an int .

 if (response == 'Y')

You forgot to actually read the user input. Your compiler should have warned you for using response uninitialized.

 else (response == 'N')

This is the cause of the error you get. else has no condition. else is the case for "none of the other conditions are true ". You either want else if or no condition here.

Correct code could look like this:

#include <iostream>
int main() {
    char response;
    std::cout << "is your circuit a parallel circuit?";
    std::cin >> response;
    if (response == 'Y') {     
        std::cout << "YES";
    } else if (response == 'N') {
        std::cout << "NO";
    } else {
        std::cout << "invalid input";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM