【问题标题】:Ending a do while loop in C++ with a phony value用假值结束 C++ 中的 do while 循环
【发布时间】:2017-03-28 09:38:00
【问题描述】:

我很难弄清楚如何在 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 循环应该具备什么条件才能停止处理值?

【问题讨论】:

  • 所以用户“你想继续吗?”,如果没有,则退出循环。
  • 暂时忘记代码。从用户的角度来看,您希望程序如何运行?

标签: c++ do-while


【解决方案1】:

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

char temp4
std::cin>>temp4;

if(temp4!='y')
break; //exits the loop

或在

中引入条件
while(temp4=='y');

【讨论】:

  • 如果我输入 Y 程序退出。不是我所期待的。
【解决方案2】:

如果你想直到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;
}

【讨论】:

    猜你喜欢
    • 2020-08-26
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 2016-08-24
    • 2018-04-06
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多