I found that I needed to start using getline(cin, input); for my user inputs. I figured out how to use stringstream to convert a string from a user into an int, so that I can store and use the numbers in math functions.
As an example, say you need to ask a user for a Student ID, you can easily store that as a string as it is rare that you would need to do any type of mathematical equations with it. However, if you were to ask for grades, that you would need to average out and convert to GPAs, that is another story.
I essentially would like to ask the user to input a number via getline, then convert the input into an int, but as a function so that I don't need to type the same deal out every time I need something converted.
Example:
#include<iostream>
#include<conio.h>
#include<string>
#include<sstream>
using namespace std;
class students{
int s1, s2, s3;
string name, id, input;
public:
void getData(){
cout << "Enter ID: ";
getline(cin, id);
cout << "Enter Name: ";
getline(cin, name);
while(true){
cout << "Enter grades for Math: ";
getline(cin, input);
stringstream convert(input);
if(convert >> s1)
break;
cout << "Invalid Grade; Please Try Again! " << endl;
}
while(true){
cout << "Enter grades for Science: ";
getline(cin, input);
stringstream convert(input);
if(convert >> s2)
break;
cout << "Invalid Grade; Please Try Again! " << endl;
}
while(true){
cout << "Enter grades for English: ";
getline(cin, input);
stringstream convert(input);
if(convert >> s3)
break;
cout << "Invalid Grade; Please Try Again! " << endl;
}
}
void showData(){
cout << "\n" << id << "\t" << name << "\tMath: " << s1 << "\tScience: " << s2 << "\tEnglish: " << s3;
}
};
int main(){
students s[20];
int i, numOfStudents;
string input;
while(true){
cout << "\nNumber of Students? ";
getline(cin, input);
stringstream convert(input);
if(convert >> numOfStudents)
break;
cout << "Invalid Grade; Please Try Again! " << endl;
}
for(i = 0; i < numOfStudents; i++){
s[i].getData();
}
for(i = 0; i < numOfStudents; i++){
s[i].showData();
}
_getch(); //Only there to keep the command line window open.
return 0;
}