简体   繁体   English

即使退出条件满足并进入,错误消息仍会打印

[英]Error message still printing even though exit condition met and entered

I'm having quite the issue trying to figure out why these code segments are printing the error message even when I have done cout statements within the block that should return true / not print that error message. 我遇到了一个相当大的问题,试图弄清楚为什么这些代码段即使在应该返回true或不打印该错误消息的块中执行了cout语句,也为什么会打印错误消息。 Any ideas? 有任何想法吗? I'm new here so please let me know if this isn't allowed. 我是新来的,所以如果不允许这样做,请告诉我。 Thanks! 谢谢!

Use of function: 使用功能:

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;
        }

Function for adding student to array: 用于将学生添加到数组的函数:

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;
}

You have an extra ; 你有一个额外的; after your if (added==false) statement. if (added==false)语句之后。 This will terminate the if statement and the code after will run regardless of the check. 这将终止if语句,之后的代码将运行,无论是否进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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