输入特定数字时中断循环
Breaking a loop when entering a specific number?
当用户输入一系列数字后输入 0 时,我将如何中断循环?对于这个项目,我正在尝试读取一个数字出现的时间。
示例:如果用户输入 1 5 6 9 8 7 1 3 5然后程序会去
1 appeared 2 times
5 appeared 2 times
6 appeared 1 time
。等等,
我的另一个问题是,如何只打印用户输入的元素而不是打印所有元素?我真的很感激任何帮助。谢谢!
#include <iostream>
using namespace std;
void nums(int[]);
int main() {
cout << "Enter the however much numbers between 1-100 that you want, when you are done type 0 to finish: " << endl;
int myarray[100] = { 0 };
for (int i = 0; i < 100; i++) {
cin >> myarray[i];
if (myarray[i] == 0) {
break;
}
}
nums(myarray);
system("pause");
return 0;
}
void nums(int myarray[]) {
for (int i = 0; i < myarray[i]; i++) {
cout << myarray[i] << " "; //This code only prints out all the elements if the user inputs numbers in order. How do I get it to print out the elements the user inputs?
}
}
我使用每个元素的索引来保存实际值和该索引的值,希望它有所帮助:
#include <iostream>
#include <vector>
int main() {
//create a vector with size 100
std::vector<int> numberVector(100);
//init all elements of vector to 0
std::fill(numberVector.begin(), numberVector.end(), 0);
int value;
std::cout << "Enter the however much numbers between 1-100 that you want, when you are done type 0 to finish: " << std::endl;
while (true) {
std::cin >> value;
//braek if 0
if (value == 0) {
break;
}
//++ the value of given index
++numberVector.at(value);
}
//for all elements of the vector
for (auto iter = numberVector.begin(); iter != numberVector.end(); ++iter) {
//if the count of number is more than 0 (the number entered)
if (*iter > 0) {
//print the index and count
std::cout << iter - numberVector.begin() << " appeared " << *iter << " timesn";
}
}
//wait for some key to be pressed
system("pause");
return 0;
}
编辑:如果您不使用c ++ 1z,请将auto iter
替换为std::vector<int>::iterator iter
相关文章:
- 我的代码运行良好,但在游戏循环中中断
- 使用 UDP 中断 while()-循环
- 如何使用中断停止循环?
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 使用 shared_ptr 在中断时结束多线程循环
- 为什么我的 while 循环对于特定输入中断,而对于其他输入工作正常?
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- C 从另一个函数中断循环
- 使用 while(1) 但在 C++ 中无法中断循环
- 输入特定数字时中断循环
- 干净编码:如何从循环中的函数调用内部中断循环
- nullptr 不会在以零结尾的字符串上中断循环
- 使用 std::weak_ptr 和别名构造函数中断循环引用:声音或有问题
- 用功能中断循环
- g++优化中断循环
- 无法使用 cin.get 来检测周期来中断循环
- 返回内部循环以C++中断循环
- OpenMP 不支持中断循环
- while语句中断循环
- 如何在Linux应用程序上使用C++中的终端输入中断循环/进程