输入特定号码时打破循环?

时间:2017-11-05 00:36:35

标签: c++ loops

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

}

1 个答案:

答案 0 :(得分:0)

我使用每个元素的索引来保存实际值,并将计数作为该索引的值,希望它有所帮助:

#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 << " times\n";
        }
    }

    //wait for some key to be pressed
    system("pause");
    return 0;
}

编辑:如果您未使用c ++ 1z,请将auto iter替换为std::vector<int>::iterator iter