loops - How to repeat an input command if input is invalid in c++ -


i have write program calculates gpa several user inputs.

i've gotten program correctly calculate gpa if inputs correct, however, program must have error checking i.e. if user inputs 5 when inputs needs 0,1,2,3, or 4. need able tell user input invalid , have program go step , allow them retry.

the program cannot use arrays.

#include <iostream> using namespace std; int main () {  //defining variables used during code. float credithours; int lettergrade; float total; float totalcredits = 0; float totalpoints = 0; //asking input user cout<<"please enter grade class: 4 a, 3 b, 2 c, 1 d, 0 f,  or  '-1' when you're done inputting grades:\n";      cin >> lettergrade; // logic ensure valid letter grade input if ((lettergrade >= 4) && (lettergrade <= 0)) {     cout << "please enter valid input (0, 1, 2, 3, or 4):\n";     cin >> lettergrade; }  cout << "please enter credit hours entered grade: \n";  cin >> credithours;   //initializing loop more grade inputs //fix loop while (lettergrade != -1) {      //updating totals     total = lettergrade * credithours;     totalpoints = totalpoints +  total;     totalcredits = totalcredits + credithours;      cout << "please enter grade class: 4 a, 3 b, 2  c, 1 d, 0 f, or -1 when you're done inputting grades:\n";      cin >> lettergrade;      if (lettergrade != -1)     {         cout << "please enter credit hours entered grade: \n";          cin >> credithours;     } }//close loop //incomplete/questionable  if (totalcredits <= 0) {     cout << "please sure credit hours add positive, non-zero value\n"; } else if (totalcredits > 0) {     //calculating , printing final gpa.     float gpa = totalpoints / totalcredits;      cout << "your gpa is:"<< gpa <<endl; } return 0; 

guga00 answer seems correct. also, note should change condition check valid letter. you're checking if lettergrade both bigger 4 , smaller 0, never true. try use following:

if ((lettergrade > 4) || (lettergrade < -1)) 

i changed && (and) || (or). checks if lettergrade either bigger 4 or smaller -1. return true if input invalid. i've added -1 allow detect end of input.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -