I have a program the I have compiled in Dev C++ and VC++ sucessfully. I want to add some more parameters to it. I'm a beginner with C++. What I need to do is cause the current working program I got to keep going until the user decides to quit. In other words, after the average is obtained, the user can then enter the grades for another student. Can anyone give me some pointers? Any help would be greatly appreciated. My code is below:
#include <iostream>
using namespace std;
int main()
{
cout << "Input the number of student grades: ";
int grades;
cin >> grades;
double num;
double sum;
sum = 0.0;
for (int x = 1; x <= grades; x++)
{
cout << "#" << x << " = ";
cin >> num;
sum += num;
}
cout << "Grades = " << grades << "\nSum = " << sum << "\nAverage = " << sum / grades << "\n";
@Scipio: Inputing a number without any validating is asking for trouble. If the user accidentally enters a letter your code goes into an infinite loop.
I know. I normally use this function to get an integer:
1 2 3 4 5 6 7 8 9 10 11 12
int getint(int max)
{
int input;
while (input<1||input>max)
{
char temp[100];
std::cin.getline(temp, 100);
input=strtol(temp,0,10);
if (input<1||input>max)
std::cout<<"Not an option!\n";
}
}
But i didnt want to confuse benjacl with that stuff :)
@benjacl
Zaita's code is a good and simple solution. Use that one
You where right :)
I needed the function where 0 was a valid input. I changed the function into this:
1 2 3 4 5 6 7 8 9 10 11 12
int getint(int min, int max)
{
int input;
while (input<min||input>max)
{
char temp[100];
std::cin.getline(temp, 100);
input=strtol(temp,0,10);
if (input<min||input>max)
std::cout<<"Not an option!\n";
}
}
That example may work with when using a "while" loop. But for this code I am trying to find a solution using the "for" loop. Thanks for the help so far.