有没有办法在 C++ 中用 char 结束循环?

Is there a way i could end a loop with a char in c++?

我是编程新手,目前我正在尝试围绕 C++ 寻找出路。我正在开发一个程序,该程序将向用户显示有关员工的基本信息,并且我希望该程序在用户输入一个字符时结束。但是,在完成它的过程中,我遇到了一个问题。当我输入 char (x) 时,它以某种方式从 1-120 循环(正如您在下面的计数器中看到的),但是当我输入它的 ASCII 码 (120) 时,它按预期结束了程序。谁能给我解释一下,可能的解决方案是什么?

#include <iomanip>
#include <iostream>

using namespace std;
class Employee
{
public:
    int Age;
    string Name;
    int ID;

    void information()
    {
        cout << "Name: " << Name << endl;
        cout << "Age: " << Age << endl;
        cout << "ID: " << setfill('0') << setw(3) << ID << endl;
    }

    Employee(string name, int age, int id)
    {
        Name = name;
        Age = age;
        ID = id;
    }
};

void createProfile()
{
    int age;
    int id;
    string name;
    cout << "Enter the Employee Name: ";
    cin >> name;
    cout << "Enter the Employee Age: ";
    cin >> age;
    cout << "Enter the Employee ID: ";
    cin >> id;
}
int main()
{
    int num, counter;
    const char stop = 'x';

    cout << "Choose an Employee " << endl;
    cout << "001 Jack" << endl;
    cout << "002 Susan" << endl;
    cout << "003 to create profile" << endl;
    cout << "Press x to Exit";
    for (num = 0; num != stop; num++)
    {
        cout << "\n\nEnter the Employee ID: ";
        cin >> num;
        counter += 1;
        if (num == 001)
        {
            Employee jack = Employee("Jack", 25, 001);
            jack.information();
        }
        else if (num == 002)
        {
            Employee jack = Employee("Susan", 23, 002);
            jack.information();
        }
        else if (num == 003)
        {
            createProfile();
        }
        else
        {
            cout << "Input invalid";
        }
    }
    cout << "\n" << counter;
}

当然可以。在 C/C++ 中,char 是一种可以用其字符值(例如 'A')或数值 (65) 表示的类型。但是,一个数字的数值不等于它自己。

'1' == 49

120 是小写 x 的 ASCII 值,并且由于您使用 int 循环,因此它最终会以您不希望它工作的方式工作是合乎逻辑的。你可以改变你的

for (num = 0; num != stop; num++)

for (num = 0; ch != stop; num++)

当然 ch 应该在循环之前声明为 char 。另外,确保将 cin >> num; 替换为 cin >> ch;