【问题标题】:Won't let me read in user input in after IF statement (homework)不让我在 IF 语句后读入用户输入(作业)
【发布时间】:2015-05-07 13:35:40
【问题描述】:

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

我的输出如下所示:

您想添加新媒体吗?为电影输入 M 或为软件输入 S:m 输入电影的名称(20 个字符或更少)名称:输入电影的评分 你的电影 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);
}

【问题讨论】:

标签: c++ cin


【解决方案1】:

问题在于,当您的 cin >> 语句忽略“\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/

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多