为什么循环内不重置字符串?



我正在为班级制作一个小型桌面成本程序。我想在其中包括一个循环。但是,每当我到达程序的结尾并将其循环回开始时,它都会跳过我要求客户姓名的部分,并将其留为空白。任何想法如何修复?

这是我的代码:

#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.ignore()。当您使用CIN获取" CH"变量时,Newline字符仍存储在输入缓冲区中。致电cin.ignore(),忽略该字符。

如果不这样

您还可以使" CH"变量成为" cname"之类的字符串,并使用getline代替CIN。那么您就不必发出cin.ignore()呼叫。

#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;
}

最新更新