输入特定数字时中断循环

Breaking a loop when entering a specific number?

本文关键字:中断 循环 数字 输入      更新时间:2023-10-16

当用户输入一系列数字后输入 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