【发布时间】:2016-05-16 02:25:21
【问题描述】:
这里是初级程序员,我遇到了字符串输入问题 程序的结构——我无法成功存储字符串 年份、流派和导演的用户输入。我尝试不使用 cin >> with getline,只使用 get() 和 getline() - 但错误仍然存在 字符串输入未正确存储。 EX:如果用户输入选项“B”, 并将输入的年份字符串“2015”存储到字符串变量whatYear中,它 导致未正确存储的错误。如何解决?
#include <iostream>
#include <cctype>
#include <string>
void printYear();
void printGenre();
void printDirector();
using namespace std;
int main(){
char choice;
用户将输入一个选项:“B”代表年份,“C”代表流派,“D”代表导演。
cout << "Hello movie'goer, please select one of the following choices:\n\n"
<< "B - Display movies in a specific year\n"
<< "C - Display movies in a specific genre\n"
<< "D - Display movies from a specific director\n\n"
<< "Enter your choice: ";
choice = cin.get();
//Input validation
while (toupper(choice) != 'B' && toupper(choice) != 'C' &&
toupper(choice) != 'D') {
cout << "Choice is invalid, the choice must be one of the following:'B', 'C', or"
<< " 'D'. Re-enter your choice: ";
choice = cin.get();
}
cout << endl << endl;
这是它处理选择的地方。 “B”将打印字符串年份输入,“C”将打印字符串流派输入,“D”将打印字符串导演姓名输入。
switch(choice)
{
case 'a':
case 'A': break;
case 'b':
case 'B': printYear(); break;
case 'c':
case 'C': printGenre(); break;
case 'd':
case 'D': printDirector(); break;
}
}
当为年份输入选项“B”时,我无法将年份输入存储到字符串变量 whatYear 中。
void printYear()
{
string whatYear;
cout << "Enter a specific year: " << endl;
getline(cin, whatYear);
我检查了字符串输入是否存储成功,但是失败了。
cout << "The input stored in string whatYear is: " << whatYear;
}
我在这里也遇到了同样的问题,字符串输入没有成功存储到字符串变量 whatGenre 中。
void printGenre()
{
string whatGenre;
cout << "Enter a specific genre: " << endl;
getline(cin, whatGenre);
cout 语句在此处显示不正确。
cout << "The input stored in string whatGenre is: " << whatGenre;
}
其他两个函数也有同样的问题。
void printDirector()
{
string whatDirector;
cout << "Enter a specific director " << endl;
getline(cin, whatDirector);
cout << endl << "The input stored in string whatGenre is: " << whatDirector;
}
【问题讨论】:
标签: c++ string function vector input