Preventing user input from being read after IF statement (homework)

I am having some problems with my simple dvd directory creation and software import to csv file code. I'm working fine, but for some reason my program is missing my first piece of code. If I choose the IF statement, this bit of code works, so I don't understand why.

my output looks like this:

Do you want to add new media? Enter M for a movie or S for software: m Enter a movie title (20 charters or less). Name: Enter the rating for your movie 1-5:

I am not getting any errors in my compiler (Visual Studio 2013) and it doesn’t allow me to enter the name and skips the right to the rating. Any explanations or suggestions would be appreciated as I want to fix this before moving on to adding more.

here is my code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){ 
string typeM = "movie";
string typeS = "software"; 
char answer, mediainput; 
int rating = 0; 
string dir, type;
string moviename,softname; 

do
{  
  cout << "Would you like to add new media? Enter M for Movie or S for software: ";
cin >> mediainput;
cout << endl;

if (mediainput == 'm' || mediainput == 'M')  
{   
cout << "Enter the name of the Movie (20 Chararters or less) \n Name: ";
getline(cin, moviename);
cout << endl;
cout << "Enter a rating for your movie " << moviename << " 1-5 ";
cin >> rating;
if (rating < 1 || rating > 5)
 {
  cout << "You must enter a number from 1 to 5. Enter a number rating: ";
  cin >> rating;
  cout << endl;
 }

ofstream outdata("DVD_Software_inventory.csv", ios_base::app);
outdata << moviename << "," << typeM << "," << rating << "," << endl;
outdata.close();
}

if (mediainput == 's' || mediainput == 'S')
{
cout << "Enter the name of the software (20 Chararters or less) \n Software   name: " << endl;
getline(cin, softname);
cout << "Enter the directory it is in \n Directory: ";
cin >> dir;

ofstream outdata("DVD_Software_inventory.csv", ios_base::app);
outdata << softname << "," << typeS << ",," << dir << "," << endl;
outdata.close();

}
cout << "\n\nWould you like to add more? Y/N ";
cin >> answer;
cout << endl;
if (answer == 'N' || answer == 'n')
 {
  cout << "** End of Program **" << endl;
  break;
 }


} while (answer == 'Y' || answer == 'y');

system("pause");
return(0);
}

      

+3


source to share


1 answer


The problem is that as long as the cin -> operator ignores "\ n" (newline character), the character is still in the cin buffer. getline (), however, does not ignore the "\ n" character.

Hence, the solution is to explicitly tell cin to ignore the "\ n" character:



cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, moviename);

      

(credit http://www.cplusplus.com/forum/beginner/24470/ )

0


source







All Articles