簡體   English   中英

我對此數組代碼有問題,該數組代碼應該輸出用戶事先輸入的所有數字

[英]I'm having a problem with this array code that is supposed to output all the numbers that were input prior by the user

所以,這就是我想要的方式:

我想讓我的程序詢問用戶將輸入多少個數字(例如5)。 輸入數字后,我希望程序輸出這些數字(例如2、3、20、40、50)。

容易吧? 好吧,我的代碼有一個問題:即使我輸入10或200作為要輸入的數字量,程序仍會停止在第6個數字處停止並僅輸出這6個數字。

int main() 
{
    int arraySize;
    int array[arraySize];
    cout << "How many numbers would you like to visualize?" << endl << "Numbers: ";
    cin >> arraySize;
    cout << "You will visualize " << arraySize << " numbers." << endl << "Begin: " << endl;
    for (int i = 0; i < arraySize; i++) {
        cin >> array[i];
    }
    cout << "You have inserted the following numbers: " << endl;

    for (int a = 0; a < arraySize; a++) {
        cout << array[a] << " ";
    }
}

如果我輸入10作為arraySize,它將停止在6。

如果要在運行時確定數組的大小,則需要一個適合該大小的容器。 由於此問題是用C ++標記的,因此您應該使用一些標准庫容器。

在您的情況下, std::vector是最佳選擇:

#include <iostream>
#include <vector>

int main()
{
  size_t arraySize = 0;
  std::cout << "How many numbers would you like to visualize?\n"
            << "Numbers: ";
  std::cin >> arraySize;
  std::cout << "You will visualize " << arraySize << " numbers.\n"
            << "Begin: \n";

  // declare std::vector and allocate memory for arraySize elements
  std::vector<int> array(arraySize);
  for (int i = 0; i < array.size(); i++) {
    std::cin >> array[i];
  }
  std::cout << "You have inserted the following numbers: \n";

  for (int a = 0; a < array.size(); a++) {
    std::cout << array[a] << " ";
  }
  std::cout << std::endl;
}

考慮用戶仍然可以輸入自己喜歡的任何內容,例如字符串。 一種改進(也是一種好的做法)將是驗證用戶輸入。

通過使用自己定義的方法int array[arraySize]您收到后arraySize作為用戶輸入解決您的問題。 聲明可變長度數組是無效的C ++。 如果啟用更多的編譯器警告,您將對此有所注意。

例如,將gcc 8.2.0與標志-Wpedantic可得出以下結果:

warning: ISO C++ forbids variable length array 'array'

這里:

int arraySize;
int array[arraySize];

不上班。 首先,可變長度數組不是C ++的一部分,因此僅在編譯器允許的情況下才進行編譯。 但是另一個問題是您要使用arraySize大小來制作數組,但是arraySize沒有初始化。 這表現欠佳-可能會發生任何事情,並且無法保證。

您需要讀取所需的arraySize (使用cin >> arraySize; ), 然后需要制作數組。 當您執行此操作時,請嘗試以下操作,而不是VLA:

std::vector<int> array(arraySize);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM