Hi. I'm a newbie to C++ still and have yet to learn classes (next chapter, might do it later). But I originally had this program in C (where I also had input buffer issues) but I wanted to try some C++ to make stuff simpler to write (and so far I'm liking it). However, when I was converting my job database program from C to C++ (rewriting it) I ran into the same input buffer problem again where the input buffer is storing the newline character. But I am using a switch statement so I can't get a string with getline as switch's must be integers.
Here's my code (Which I commented to make it easy to read)
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void writeinfo();
void readinfo();
void menu();
int main()
{
menu();
cout << "Program exiting..." << endl;
return 0;
}
void menu()
{
int choice;
//********Start Menu Display
cout << "What would you like to do?" << endl;
cout << "1. Enter employee information" << endl;
cout << "2. Read employee information" << endl;
cout << "3. Exit" << endl;
//********End Menu Display
cout << "Enter a number: ";
cin >> choice;
//**********Start Choice Switch*************
switch (choice)
{
case 1:
writeinfo();
break;
case 2:
readinfo();
break;
case 3:
return;
default:
cout << "Please enter 1, 2, or 3 ONLY." << endl;
menu();
}
//**********End Choice Switch************
}
void writeinfo()
{
string name, job, id;
ofstream jobFile("jobdatabase.txt", ios::app);
if (!jobFile)
{
cout << "ERROR: Could not open jobdatabase.txt" << endl;
menu();
}
else
{
// ********Start Getting Information**********
cout << "Please enter the worker's id number: ";
getline(cin,id);
cout << "Please enter the worker's name: ";
getline(cin,name);
cout << "Please enter the worker's duty: ";
getline(cin,job);
//*************End Get Info************
//*************Start Write Info********
jobFile << "Worker's id number: " << id << " Worker's name: " << name;
jobFile << " Worker's Job: " << job << endl;
jobFile.close();
//*************End Write Info**********
menu();
}
}
void readinfo()
{
string databaseinfo;
ifstream jobFile("jobdatabase.txt");
if (! jobFile)
{
cout << "ERROR: Could not open jobdatabase.txt" << endl;
menu();
}
else
{
//**********Start Reading Information **********
while (!jobFile.eof())
{
getline(jobFile,databaseinfo);
cout << databaseinfo << endl;;
}
jobFile.close();
//**********End Reading Information ************
menu();
}
}
Basically, everything works except this input buffer issue that is causing it to skip over the worker id number entry input. Advice would be appreciated. Thanks.