简体   繁体   中英

I'm having a problem with reading a string in an if statement

I'm a beginner in C++ coding and I have a problem with an assignment question:

Write a C++ program that prompts the user to enter two characters and displays the major and status represented in the characters. The first character indicates the major and the second is number character 1, 2, 3, 4, which indicates whether a student is a freshman, sophomore, junior, or senior. Suppose the following characters are used to denote the majors:
M: Mathematics
C: Computer Science
I: Information Technology

This is what I tried so far:

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

int main()
{
    string i;
    cout <<"Enter two characters: ";
    cin>> i;
    i[0]=toupper(i[0]);
    if (i[0]=='M')
    {
        if (i[1]==1)
        {
            cout<<"Mathematics Freshman."<<endl;
        }
        else if (i[1]==2)
        {
            cout<<"Mathematics Sophomore."<<endl;
        }
        else if (i[1]==3)
        {
            cout<<"Mathematics Junior."<<endl;
        }
        else if (i[1]==4)
        {
            cout<<"Mathematics Senior."<<endl;
        }
        else
        {
            cout<<"Invalid status code."<<endl;
        }
    }
    return 0;
}

When I run and type for example "m1" it should print "Mathematics Freshman." , but it prints "invalid status code" , which is the output from the else statement, and I don't know why.

You should compare a character to character instead of the integer. Try this

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string i;
    cout <<"Enter two characters: ";
    cin>> i;
    i[0]=toupper(i[0]);
    if (i[0]=='M')
    {
        if (i[1]=='1')
        {
            cout<<"Mathematics Freshman."<<endl;
        }
        else if (i[1]=='2')
        {
            cout<<"Mathematics Sophomore."<<endl;
        }
        else if (i[1]=='3')
        {
            cout<<"Mathematics Junior."<<endl;
        }
        else if (i[1]=='4')
        {
            cout<<"Mathematics Senior."<<endl;
        }
        else
        {
            cout<<"Invalid status code."<<endl;
        }
    }
     return 0;
}

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