根据特定的用户输入量结束 while 循环

End a while loop based on specific amount of user input?

本文关键字:结束 while 循环 输入 用户      更新时间:2023-10-16

我想知道是否有办法根据用户输入的数量递增和终止 while 循环? 比如,让用户输入一个号码,对所述号码执行某些操作,然后提示输入新号码,冲洗并重复 (x( 次?

这是我的代码,或者缺乏它,哈哈。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    int num_1, num_2, num_3, num_4, num_5;
    //while(user inputs <= 5)
    // cout << "Enter a number" << endl;
    // print that number
    // sum number to total
    // print sum
    // return to beginning of loop

    return 0;
}

是的,你可以这样做。您只需要一个计数器来保存有关循环执行次数的信息:

#include <iostream>
int main() {
    int input = 0;
    int sum = 0;
    int user_input = 0; // counter for loop executions
    while (user_input < 5) { // while the loop executed fewer than 5 times, execute the code...
        ++user_input; // ... and mark that the loop executed one more time
        // code logic:
        std::cout << "enter a number: ";
        std::cin >> input;
        sum += input;
        std::cout << "the input: " << input << 'n';
        std::cout << "sum so far: " << sum << 'n';
    }
}