Terminate a loop with a char

I would like the loop to terminate when the user enters q, to quit. Here is what I have so far:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string firstNameFromUser;
string lastNameFromUser;
float userGrades;
float userAvg;
//Initalize the sum of the grades and the counter to zero
float sumofGrades = 0;//Sum of the grades
int numberofGrades = 0;//Grade counter
//Output file stream
ofstream userNameandAvg;

system("cls");//Preforms a system call to cls and clears the screen

cout << "Please enter your first and last name: " << endl;//Prompts the user to enter their first and last name
cin >> firstNameFromUser >> lastNameFromUser;//Reads in the first and last name from user and stores them in their respective string variables

cout << "Please enter your grades and press q to quit: " << endl;//Prompts user to enter their grades
cin >> userGrades;//Takes in the grades from user and stores them in the float variable

while (userGrades)
{
while (userGrades < 0)
{
cout << "The last number you entered is negative. Please enter a positive number: " << endl;//If the user enters a negative number, prompts the user to enter a positive number
cin >> userGrades;//Takes in the grades from user and stores them in the float variable
}
if (userGrades >= 0)
{
sumofGrades = sumofGrades + userGrades;
numberofGrades++;
cin >> userGrades;
}
}

userAvg = sumofGrades / numberofGrades;//Calculates the user's average grade
//Open output file stream
userNameandAvg.open("ee261_grade.txt");//Creates and stores the grade report in ee261_grade.txt
userNameandAvg << firstNameFromUser << " " << lastNameFromUser << ", " << "your average grade is: " << userAvg << "%" << endl;//Prints the user's name and average grade in ee261_grade.txt
//Close output file stream
userNameandAvg.close();

return 0;
}
Last edited on
Hello. Please Edit your post and use code tags for your code, it's otherwise hard to read - http://www.cplusplus.com/articles/jEywvCM9/

If you want it to terminate when the user enters q. All you would need is a loop with that condition.

Either a while loop, or a do while loop.

1
2
3
4
5
6
7
8
char user_answer = 'x';
while (user_answer != q)
{
   //all code
   
   cout >> "want to quit? Then enter q" << endl;
   cin >> user_answer;
}

Topic archived. No new replies allowed.