在IF语句(家庭作业)

时间:2015-05-07 13:35:41

标签: c++ cin

我在制作DVD和DVD的简单代码方面遇到了一些问题。要导入到csv文件的软件列表。 我的输出工作正常但由于某种原因,我的程序正在跳过我的第一部分代码。如果我拿出IF语句,那段代码就可以了,所以我不明白为什么。

我的输出如下:

  

您要添加新媒体吗?为电影输入M或为软件输入S:m   输入电影的名称(20个或更少的Chararters)名称:输入评级   你的电影1-5:

我的编译器(Visual Studio 2013)中没有出现任何错误,并且它不允许我输入名称并跳过评分权限。 任何解释或建议都会受到赞赏,因为我想在我继续添加更多内容之前解决这个问题。

这是我的代码:

#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);
}

1 个答案:

答案 0 :(得分:0)

问题是,当你的cin&gt;&gt;语句忽略“\ n”(换行符),该字符仍然在cin的缓冲区中。 getline()然而, 不会忽略“\ n”字符。

因此,解决方案是明确告诉cin忽略“\ n”字符:

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

(归功于http://www.cplusplus.com/forum/beginner/24470/