在尝试打破while循环时陷入无限循环

Der*_*k H 1 c++ loops function

所以我正在制作一个带有主菜单的计算器,我想让操作继续,直到用户按下$然后返回主菜单.当我测试它时,它会将我的代码抛入无限循环中.我做错了什么?下面是一个功能的片段.(菜单被声明为无效)

float makeSum(float num1, float num2) {

float r = 0;
bool ended = false;
do {
    cout << "Please provide the first number: " << endl;
    cin >> num1;

    if (num1 == '$') {
        ended = true;
    }

    cout << "Please provide the second number: " << endl;
    cin >> num2;

    if (num2 == '$') {
        ended = true;

    r = num1 + num2;
    cout << "Result: " << r << endl;
} while (!ended);

menu();
return r;

}
Run Code Online (Sandbox Code Playgroud)

小智 5

这肯定不会起作用.当你说:

float num2;
Run Code Online (Sandbox Code Playgroud)

然后:

cin >> num2;
Run Code Online (Sandbox Code Playgroud)

然后只从输入流中读取浮点数.解决这个问题的一种方法是在你的循环内部:

string input;
...
cin >> input;
if (input == "$") break;
istringstream s(input);
float num;
s >> num; // now you read a float from the string
Run Code Online (Sandbox Code Playgroud)

另一件事是,使用break我在上面的代码片段中显示的循环更容易打破循环,而不是使用布尔标志并检查它.