c++ I am writing a program with a menu. I am using a do while loop and a switch statement to execute the menu. I am calling functions into the different cases. When i call a function that has cin in it my program skips over the cin. How can i get the cin to work in my switch statement?
here is the function for my menu. after researching i tried different formats that aren't working.
case 1, 2, and 5 are not working.
void Execute_Main_Menu(Student &Temp, Student List[], int File_Size, ifstream &fin)
{
char Choice ;
ofstream fout ;
do
{
cout << "\n\nWhat would you like to do? Enter 1-8: " ;
cin >> Choice ;
Student Temp ;
switch(Choice)
{
case '1' :
{
File_Size=Read_Data(List, CAP) ;
Another_Task() ;
break ;
}
case '2' : Open_Output_File(fout) ;
Print_List_To_File(List, File_Size, fout) ;
Another_Task() ;
break ;
case '3' : Sort_Menu() ;
Execute_Sort_Menu(List, File_Size) ;
Another_Task() ;
break ;
case '4' : Print_List(List, File_Size) ;
Another_Task() ;
break ;
case '5' : Print_Student(Temp, List, File_Size) ;
break ;
case '6' : cout << "F" ;
break ;
case '7' : cout << "G" ;
break ;
case '8' : cout << "\n\nThank You. Good Bye." ;
exit (0) ;
default : cout << "\nBad Input. Must be 1-8." ;
}
}
while(Choice != 8);
}
here are examples of cin in functions i am calling
bool Open_Output_File(ofstream &fout)
{
string Output ;
cout << "\nEnter the name of the output file: " ;
getline(cin, Output) ;
fout.open(Output.c_str()) ;
if (fout.fail())
return false ;
else
return true ;
}
void Execute_Sort_Menu(Student List[], int File_Size)
{
char Choice ;
do
{
cout << "\nWhat would you like to do? Enter 1 or 2: " ;
cin >> Choice ;
switch(Choice)
{
case '1' : Sort_B_Last_Name(List, File_Size) ;
Print_List(List, File_Size) ;
break ;
case '2' : Sort_B_Average(List, File_Size ) ;
Print_List(List, File_Size) ;
break ;
default : cout << "\nYou have to enter the number 1 or the number 2." ;
}
}
while(Choice !='1' && Choice !='2');
}
bool Open_Input_File(ifstream &fin)
{
string Input ;
cout << "Enter the name of the input file: " ;
getline(cin, Input) ;
fin.open(Input.c_str()) ;
if (fin.fail())
return false ;
else
return true ;
}
int Read_Data(Student List[], int Size)
{
ifstream fin ;
int i = 0;
if (Open_Input_File(fin)== true )
{
string Course_Name, Course_Id, Location ;
getline(fin, Course_Name) ;
getline(fin, Course_Id) ;
getline(fin, Location) ;
Read_Student(List[i], fin);
while(!fin.eof())
{
i++ ;
if(i == Size)
{
cout << "\nArray is full.\n" ;
return (i);
}
Read_Student(List[i], fin);
}
}
else
{
cout <<"\nBad File Name. Did not open. Program terminated.\n\n";
exit(0);
}
return (i);
fin.close() ;
}
Best Answer
I took your code and cut out the main switch logic: This works. I added a second function with a cin statement, it calls appropriately.
I suspect it is how you are using getline. You could try using cin for strings too...
Also, when you open a file, if it succeeds, you should remember to close it.