这个问题在这里已有答案:
早些时候我发布了一个关于 cin
跳过输入的问题,我得到了刷新的结果,并使用 istringstream
,但现在我尝试了所有可能的解决方案,但没有一个工作 .
这是我的代码:
void createNewCustomer () {
string name, address;
cout << "Creating a new customer..." << endl;
cout << "Enter the customer's name: "; getline(cin, name);
cout << "Enter the customer's address: "; getline(cin, address);
Customer c(name, address, 0);
CustomerDB::addCustomer(c);
cout << endl;
}
但我仍然得到同样的东西,跳过输入,当它确实需要输入时,它需要它们并且名称中的存储空白,并且在地址中它采用我在名称中写的但是从第二个字母到结尾
我的代码出了什么问题?
我一起尝试了 cin.ignore()
, cin.get()
和 cin.clear()
所有这些,没有一个工作过
编辑:
main.cpp中的main方法仅调用 mainMenu()
void mainMenu () {
char choice;
do {
system("cls");
mainMenuDisplay();
cin >> choice;
system("cls");
switch (choice) {
case '1':
customerMenu();
break;
case '2':
dvdMenu();
break;
case '3':
receiptMenu();
break;
case '4':
outro();
break;
default:
cout << '\a';
}
cin.ignore();
cin.get();
} while (choice != '4');
}
我将为客户示例选择1,这是 customerMenu()
void customerMenu () {
char choice;
do {
system("cls");
manageCustomerMenu();
cin >> choice;
system("cls");
switch (choice) {
case '1':
createNewCustomer();
break;
case '2':
deleteCustomer();
break;
case '3':
updateCustomerStatus();
break;
case '4':
viewCustomersList();
break;
case '5':
mainMenu();
break;
default:
cout << '\a';
}
cin.ignore();
cin.get();
} while (choice != '5');
}
我再次选择1来创建一个新的客户对象,现在将转到MainFunctions.cpp,它将调用第一个函数 createNewCustomer()
.
void createNewCustomer () {
string name, address;
cout << "Creating a new customer..." << endl;
cout << "Enter the customer's name: "; cin.getline(name,256);
cout << "Enter the customer's address: "; cin.getline(address,256);
Customer c(name, address, 0);
CustomerDB::addCustomer(c);
cout << endl;
}
4 回答
在这里,cin留下的
'\n'
正在创造问题 .这个
\n
正被createNewCustomer()
中的下一个getline使用 . 你应该使用getline代替 -我认为这可以解决这个问题 .
我遇到了这个问题,并使用getchar()解决了这个问题,以捕获('\ n')新的char
菜单代码的结构是问题:
如果您在
cin >> something
之后使用getline
,则需要在两者之间刷新缓冲区 .如果不需要超过换行符的字符,我个人最喜欢的是
cin.sync()
. 但是,它是实现定义的,因此它可能与我的工作方式不同 . 对于坚固的东西,请使用cin.ignore()
. 或者如果需要,使用std::ws
删除前导空格: