0

This is a program where a user enters 5 marks, and the program calculates the average mark and grade. However, it should show an error when the user enters a string (alphabet) instead of a number. How do I do this?

#include <iostream>

using namespace std;

int main()
{
double dblMarkOne;
double dblMarkTwo;
double dblMarkThree;
double dblMarkFour;
double dblMarkFive;
double dblAverage;
string strGrade;

cout<<"Enter your first mark: ";
cin>>dblMarkOne;

while (dblMarkOne < 0 || dblMarkOne > 100)
{ 
    cout << "Enter a valid test score within 1 to 100. ";
    cout << "Enter your first mark: ";
    cin >> dblMarkOne;
}
user2766873
  • 35
  • 1
  • 1
  • 4

2 Answers2

0

Here's a simple solution. I'm sure you can tweak it a bit to improve speed.

#include <iostream>
#include <stdlib.h>     /* atoi */

using namespace std;

bool isDouble(char a[]);

int main()
{
  double dblMarkOne;    
  char a[10];

  cout<<"Enter your first mark: ";
  cin >> a;  /* read it as a char array */

  if(isDouble(a)){    
    dblMarkOne = atof(a);
    cout << dblMarkOne;
  }
  else
  {
    cout << "not a double";
  }
}

bool isDouble(char a[])
{
  int i = 0;

  while(a[i] != 0)
  {
    if(!(isdigit(a[i]) || a[i] == '.'))
    {
      return false;    
    }
    i++;
  }
  return true;
}
Anusha
  • 81
  • 2
0

Based on this answer, https://stackoverflow.com/a/3274025/1903116

do
{ 
    cout << "Enter a valid test score within 1 to 100. ";
    cout << "Enter your first mark: ";
} while (! (cin >> dblMarkOne) );
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497