【发布时间】:2017-07-14 04:47:22
【问题描述】:
我正在为一个班级制作一个小型桌面成本计划。我想在其中包含一个循环。但是每次我到程序结束并循环回到开头时,它都会跳过我询问客户姓名的部分并将其留空。知道如何解决吗?
这是我的代码:
#include <iostream> // needed for Cin and Cout
#include <string> // needed for the String class
#include <math.h> // math functions
#include <stdlib.h>
using namespace std;
#define baseCost 200.00
#define drawerPrice 30.00
int main(void)
{
while(true)
{
string cname;
char ch;
cout << "What is your name?\n";
getline(cin, cname);
cout << cname;
cout << "\nWould you like to do another? (y/n)\n";
cin >> ch;
if (ch == 'y' || ch == 'Y')
continue;
else
exit(1);
}
return 0;
}
【问题讨论】:
-
你有一个围绕 main 的 while 循环?这甚至可以编译吗? >.
-
既然您已经确定问题出在循环和字符串上,您可以将代码简化为这样吗?这让每个人都轻松多了。 (PS:
while (true) int main() { ...什么?) -
请edit您的问题提供minimal reproducible example。
-
你的复制粘贴好像坏了。
-
它有一个简化版本。 (抱歉,'while' 放置错误)
标签: c++ string loops while-loop