Confused about error message.

I'm writing a program that registers students into a class and does some other things but I'm having an issue with the function that gets the student ID. The error says "Invalid operands to binary expression (string and int). I'm not sure what the problem is. Please help? Here's the part of the code the issue is in.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 bool checkStudentID(string ID) /* check if ID is valid */
    {
            if (ID.at(0) != 'A')
            {
                return false;
            }
            else if (ID.length()!= 9)
            {
                return false;
            }
            else
            {
                return true;
            }
    }



string getStudentID() {
        /* get the student ID */
    string studentID = " ";
    
    cout << "Student ID: ";
    cin >> studentID;
    checkStudentID(studentID);
    if (studentID == true)
            return studentID;
    else
        {
           cout << "****Invalid ID****" << endl;
           cout << "ID must be written as A******** in which * is a digit." << endl;
        }
}


The error is in my "if" statement in the second function.
studentID is a string. How can a string be true, or false?

It looks to me like what you really want to be checking is the return value from checkStudentID().
Last edited on
Alright I changed the string in the if statement to the boolean function and I believe I fixed it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>

bool checkStudentID( std::string id )
{
    // note: check the length first (before attempting to access first character)
    return id.length() == 9 && id[0] == 'A' ;
}

std::string getStudentID()
{
    std::string studentID ;

    std::cout << "Student ID: ";
    std::cin >> studentID;

    if( checkStudentID(studentID) ) return studentID ; // valid id, return it
    
    else // error in input
    {
       std::cout << "****Invalid ID****\n"
                 << "ID must be written as A******** in which * is a digit.\n" ;

      return getStudentID() ; // retry input
    }
}
Topic archived. No new replies allowed.