gpt4 book ai didi

c++ - 不会让我在 IF 语句后读取用户输入(作业)

转载 作者:太空狗 更新时间:2023-10-29 23:15:15 25 4
gpt4 key购买 nike

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

我的输出是这样的:

Would you like to add new media? Enter M for Movie or S for software: m Enter the name of the Movie (20 Chararters or less)Name: Enter a rating for your movie 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);
}

最佳答案

问题是当您的 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/)

关于c++ - 不会让我在 IF 语句后读取用户输入(作业),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30102721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com