我遇到了一个相当大的问题,试图弄清楚为什么这些代码段会打印错误消息,即使我在应该返回true的块中执行了cout语句/也不会打印该错误消息。有任何想法吗?我是新来的,所以如果不允许这样做,请告诉我。谢谢!

使用功能:

case 'a':
        {
            // Format: a ID credits GPA
            // Adds a student with the given student ID (ID), number of
            // credits (credits), and overall GPA (GPA) to the database.
            // If the student is already in the database, an error
            // message should be printed indicating this.

            int credits = 0;
            double gpa = 0;
            cin >> studentID;
            cin >> credits;
            cin >> gpa;

            // Adds the student and checks to see if the student was actually added
            // or if there was an existing student with the specified ID

            bool added = addStudent(studentID, credits, gpa);
            if(added == false);
            {
                cout << "Student already exists in database, nothing changed." << endl;
                // Still prints this when executed with valid
            }
            break;
        }


用于将学生添加到数组的函数:

bool addStudent (int id, int numCredits, double gpa) {

// Check to see if student exists

if (nextEntry != 0)
{
    for (int x = 0; x < 7000; x++) {
        Student tmp = studentRecords[x];
        if (tmp.studentId == id)
        {
            return false;
            cout << "hey" << endl;
        }
    }
}

// If student does not exist, add to records database
if (nextEntry != 7000)
{
    studentRecords[nextEntry].studentId = id;
    studentRecords[nextEntry].numCredits = numCredits;
    studentRecords[nextEntry].gpa = gpa;
    nextEntry++;
    return true;
    // confirmed I can get here
}

return false;
}

最佳答案

;语句后,您还有一个额外的if (added==false)。这将终止if语句,之后的代码将运行,而与检查无关。

关于c++ - 即使退出条件满足并进入,错误消息仍会打印,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28387008/

10-09 04:12