-3

有一个包含 9 个空格(元素)的数组,其中将存储用户输入的这 9 个数字。

您如何确保他们只输入这 9 个数字并且它们不一样?
最后cout(打印)它们从小到大?

4

1 回答 1

3

这是一个确保 [0,9] 范围内的数字并忽略重复项的解决方案:

#include <algorithm> //if using copy printing
#include <iostream> //for cin and cout
#include <iterator> //if using copy printing
#include <set> //for set

CHOOSE A METHOD BELOW AND ADD THE CORRESPONDING INCLUDE

int main() {
    std::set<int> nums; //here's the array

    std::cout << "Please enter nine different numbers." 
                 "Duplicates will be ignored.\n";

    //ADD THE NEXT PART OF THE METHOD, THE DECLARATION

    do {
        std::cout << "Enter the next number: ";

        //ADD THE FINAL PART, GETTING INPUT AND INSERTING IT INTO THE SET
    } while (nums.size() < 9); //do this until you have 9 numbers

    std::cout << "The numbers you entered, in order, are:\n";

    //C++11 printing
    for (const int i : nums)   
        std::cout << i << ' ';

    //C++03 printing using copy
    std::copy (nums.begin(), nums.end(), 
               std::ostream_iterator<int> (std::cout, " "));

    //C++03 printing using an iterator loop
    for (std::set<int>::const_iterator it = nums.cbegin(); //this was to
                                       it != nums.cend();  //eliminate the
                                       ++it)               //scrollbar
        std::cout << *it << ' ';
}

第一种方法:(更好的范围更广)

#include <limits> //for numeric_limits
...
int temp; //this holds the current entry
...
//works better when you get out of the range 0-9
while (!(std::cin >> temp) || temp < 0 || temp > 9) { 
//body executes if input isn't an int between 0 and 9

    //clear bad input flag
    std::cin.clear(); 

    //discard bad input
    std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 

    //prompt for new number (could also add that you're ignoring to beginning)
    std::cout << "Invalid number. Please enter a new one: "; 
}

//insert the valid number, duplicates ignored, automatically sorted
nums.insert (temp); 

第二种方法:(更适合 0-9 范围)

#include <cctype> //for isdigit
...
char temp; //holds current entry
...
//suitable for 0-9 range 
do {
    std::cin >> temp; 
    if (!std::isdigit (temp))
        std::cout << "Invalid number. Please enter a new one: ";
while (!std::isdigit (temp));

nums.insert (temp - '0'); //add the integer value of the character processed

这里的关键是std::set,它只允许唯一的条目,并自动对元素进行排序。

于 2012-07-18T16:38:42.913 回答