I am a beginner in C++ and needs help in a code I am working on. The program is a simple one which requires the user to input a name, the program enrolled in, name of school and then the student's age. After entering the required information, the user is asked if he/she wants to encode more entries or not. If user opts to end, the screen then displays the total number of students encoded. That simple. The problem lies if the user opts to encode more entries because the input routine of requesting for the name of the student is skipped and prompts the user to enter the program enrolled. This goes on until the user opts to end. Below is the code:
// cin with strings
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int students, age;
string myname;
string program;
string school;
string encode;
int main ()
{ students = 0;
do {
system ("cls");
students = students + 1;
cout <<"Enter your name: ";
getline (cin, myname);
cout <<"Enter your Program: ";
getline (cin, program);
cout <<"Enter the name of your school: ";
getline (cin, school);
cout <<("Enter your age: " );
cin >> age;
cout <<"\n\n\n Do you want to encode more entries? Type <Y> for Yes; <N> for End: ";
cin >> encode;
} while (encode == "Y");
cout <<" A Total of " << students << " Students have registered ";
cout <<"\n\n\n\n\n Program Execution Terminated: Have a nice Day"<< endl;
system ("pause");
return 0;
}
I would greatly appreciate any help on this matter.
I'm sorry that I can't fully explain how this works but I can solve your issue. Basically it's got something to do with mixing getline() and cin. Apparantly it's best not to, I won't even attempt to explain why and confuse you because I don't quite get it yet myself but I've added a few things into your code that solve the problem. I've put a link here that explains it quite well and explains the method I used to solve the problem but if you still don't understand the issue caused then there's quite a few people on the forum (including myself) who have asked this same question so have a look around for an explanation you like.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
usingnamespace std;
int students = 0, age;
string lineAge;
string myName;
string program;
string school;
string encode = "y";
stringstream stream;
int main ()
{
do
{
system("cls");
students = students + 1;
cout <<"Enter your name: ";
getline(cin, myName);
cout <<"Enter your Program: ";
getline(cin, program);
cout <<"Enter the name of your school: ";
getline(cin, school);
cout <<("Enter your age: " );
getline(cin, lineAge);
stream << lineAge;
stream >> age;
cout <<"\n\n\n Do you want to encode more entries? (y/n) ";
getline(cin, encode);
}
while (encode == "y");
if (encode == "n")
{
cout <<" A Total of " << students << " Students have registered ";
cout <<"\n\n\n\n\n Program Execution Terminated: Have a nice Day"<< endl;
system ("pause");
}
return 0;
}