C++ 为什么不是';t字符串在循环内重置?
我正在为一个班级做一个小的课桌费用计划。我想在其中包含一个循环。但每次我到了程序的末尾,并将其循环到开头,它就会跳过我询问客户姓名的部分,并将其留空。知道怎么修吗 这是我的密码:C++ 为什么不是';t字符串在循环内重置?,c++,string,loops,while-loop,C++,String,Loops,While Loop,我正在为一个班级做一个小的课桌费用计划。我想在其中包含一个循环。但每次我到了程序的末尾,并将其循环到开头,它就会跳过我询问客户姓名的部分,并将其留空。知道怎么修吗 这是我的密码: #include <iostream> // needed for Cin and Cout #include <string> // needed for the String class #include <math.h>
#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;
}
#包括//Cin和Cout所需
#包含//字符串类所需的
#包含//数学函数
#包括
使用名称空间std;
#定义基本成本200.00
#定义抽屉价格30.00
内部主(空)
{
while(true)
{
字符串cname;
char ch;
cout问题是在提示退出后需要调用cin.ignore()。当使用cin获取'ch'变量时,输入缓冲区中仍存储有换行符。调用cin.ignore(),忽略该字符
如果没有,您会注意到程序在第二个循环中打印一个换行符作为名称
您还可以将'ch'变量设置为类似'cname'的字符串,并使用getline代替cin。这样就不必发出cin.ignore()调用
#包括//Cin和Cout所需
#包含//字符串类所需的
#包含//数学函数
#包括
使用名称空间std;
#定义基本成本200.00
#定义抽屉价格30.00
int main()
{
while(true)
{
字符串cname;
char ch;
你能不能在main周围有一个while循环?这是否可以编译?>。既然你已经确定问题出在循环和字符串上,你能把代码简化成这样吗?这对每个人来说都很容易。(P.S:while(true)int main(){…
what?)请提供您的问题。您的复制粘贴似乎已损坏。有一个简化版本。(对于“while”放置错误表示抱歉)是的!谢谢。如果有机会,请单击答案旁边的复选标记。祝您学习顺利!
#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()
{
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;
// Slightly cleaner
if (ch != 'y' && ch != 'Y')
exit(1);
cin.ignore();
/*
if (ch == 'y' || ch == 'Y')
continue;
else
exit(1);
*/
}
return 0;
}