使用假值结束 do while 循环C++

Ending a do while loop in C++ with a phony value

本文关键字:while 循环 C++ do 结束      更新时间:2023-10-16

我很难弄清楚如何在C++中结束do-while循环。我需要在处理 x 数量的数据集后停止循环。也就是说,没有固定的数据量,用户确定何时完成输入值。

我需要能够在用户决定完成输入数据时停止我的 do-while 循环。

我的主程序应该在一个循环中读入和处理 3 个整数值的组,直到数据集结束。

对于每组 3 个值,

主程序将打印这些值,然后将这 3 个值作为参数发送到另一个函数。

这是我到目前为止所拥有的:

#include <iostream>
using namespace std;
int main() {
    int temp1, temp2, temp3;
    do {
        cin >> temp1 >> temp2 >> temp3;
        cout << "The 3 values are: " << temp1 << " " << temp2 << " " << temp3 << endl;
    }
    while (****this is where I need help!*****);
    return 0;
}

我的问题是我有多个输入值,那么我怎么知道 while 循环应该具有什么条件才能停止处理值?

最简单的解决方案是引入一个新输入,该输入基于值(例如 y 或 n(执行中断操作

char temp4
std::cin>>temp4;
if(temp4!='y')
break; //exits the loop

或在

while(temp4=='y');
如果你想

这样做直到EOF,你需要break

do {
    cin >> temp1 >> temp2 >> temp3;
    if (!cin)
        break;
    cout << "The 3 values are: " << temp1 << " " << temp2 << " " << temp3 << endl;
}
while (true);

或:

while (true) {
    cin >> temp1 >> temp2 >> temp3;
    if (!cin)
        break;
    cout << "The 3 values are: " << temp1 << " " << temp2 << " " << temp3 << endl;
}