根据特定的用户输入量结束 while 循环
End a while loop based on specific amount of user input?
我想知道是否有办法根据用户输入的数量递增和终止 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';
}
}
相关文章:
- 为什么这个 while 循环在下面的代码中没有结束?
- 为什么在使用不相关的宏时会阻止 while 循环结束?
- 为什么我的 while 循环永远不会在 C++ 中的数字猜测游戏中结束?
- while 循环 C++ 结束,但不继续到其余语句
- 当满足条件时,While循环未结束
- 为什么我的 while 语句没有结束?
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 为什么 while(int) 在 int = 0 时结束?
- 根据特定的用户输入量结束 while 循环
- 使用假值结束 do while 循环C++
- C 为什么在满足布尔条件后,我的DO-while循环就无法结束
- C++ 为什么 getline() 会结束 while 循环
- 永无止境的 while-循环C++即在输入字符串 == no 时结束
- C++使用cin.get来获取一个字符,但在遇到EOF时不会结束while循环
- 如何让程序知道当我使用 while(cin>> 时文件结束
- 如何结束我的while循环
- 在结束取决于布尔值的 do/while 循环时遇到问题 - C++
- 如何结束while循环
- 结束while循环进行字符替换
- 如何在C++中使用bool sentinel值来结束while循环