Home > Enterprise >  While loop breaks early
While loop breaks early

Time:11-10

I've made a program that asks for student information (name, course and grade) and it is configured to break whenever the input name of a course or a student is stop

Here is my code:

#include <iostream>
#include <vector>

using namespace std;

int main() {

    vector<string> v;
    string name;
    string course;
    string grade;

    while (name != "stop") {
        cout << "Please type a student name: ";
        getline(cin, name);

        if (name != "stop") {
            v.push_back(name);
        }

        while (course != "stop") {
            cout << "Please type a course name: ";
            getline(cin, course);
            if (course != "stop") {
                v.push_back(course);
            }
            if(course != "stop" == 0){
                break;
            }
            else {
                cout << "Please type the grade: ";
                getline(cin, grade);
                v.push_back(grade);
            }
        }
    }



    //for (auto iter = v.begin(); iter != std::prev(v.end());   iter){
    //    std::cout << *iter << std::endl;
    //}

    return 0;
}

I want the program to ask for a new student whenever the first students course is called "stop", but that just means that whenever the new student name is typed, the while loop for "course" keeps "breaking" because the last course entered is "stop".

Any ideas on how to fix this?

Sorry if the question is elaborated badly, let me know if you need more clarification!

Thanks :)

CodePudding user response:

For starters this if statement

    if (name != "stop") {

should be enlarged and include the inner while loop that should be rewritten as a do while loop.

For example

while (name != "stop") {
    cout << "Please type a student name: ";
    getline(cin, name);

    if (name != "stop") {
        v.push_back(name);

        do
        {
            cout << "Please type a course name: ";
            getline(cin, course);

            if (course != "stop") {
                v.push_back(course);
                cout << "Please type the grade: ";
                getline(cin, grade);
                v.push_back(grade);
            }
        } while ( course != "stop" );
    }
}

Also as @Remy Lebeau wrote in a comment the outer while loop also can be rewritten as a do-while loop.

CodePudding user response:

You can just set the course variable to empty string "" in the if where you break the inner while loop.

Like this:

if(course == "stop") {
    course = "";
    break;
}
  • Related