分享
三行代码  ›  专栏  ›  技术社区  ›  Milahn

在c++中是否有清除空数组的方法,请检查下面的代码以获得解释

  •  0
  • Milahn  · 技术社区  · 1 周前
    generated = (rand() % 11);
    
    cout << "GUESS THE NUMBER 10 TIMES" << endl;
    for (int i = 0; i < 10; i++) {
      cin >> guesses[i];
    
      if (generated == guesses[i]) {
        cout << "CONGRATS ! YOU HAVE FOUND THE CORRECT NUMBER ! " << generated << endl;
        restart();
        break;
      }
    }
    cout << "HERE ARE YOUR GUESSES:" << endl;
    for (int k = 0; k < 10; k++) {
      cout << guesses[k] << endl;
    }
    

    如果数组没有填满,输出会给出猜测的值,然后在空的插槽中是随机数。是否有方法清除或删除未触及的插槽?

    1 回复  |  直到 1 周前
        1
  •  3
  •   s d    1 周前

    对。记下你接受了多少输入 c 循环到 而不是第二个循环中的10:

    int c = 0;
    cout << "GUESS THE NUMBER 10 TIMES" << endl;
    for (int i = 0; i < 10; i++) {
        cin >> guesses[i];
        c++;
    
        if (generated == guesses[i]) {
            cout << "CONGRATS ! YOU HAVE FOUND THE CORRECT NUMBER ! " << generated << endl;
            restart();
            break;
        }
    }
    cout << "HERE ARE YOUR GUESSES:" << endl;
    for (int k = 0; k < c; k++)
        cout << guesses[k] << endl;