簡體   English   中英

如何限制未知數組大小的循環大小

[英]How to limit the size of loop for unknown array size

遇到一個不知道數組大小的問題,當需要提示數組中的信息時,不知道如何限制循環的大小,只提示數組中的內容並退出環形。 最初,我為數組索引聲明 9999,因為我不知道用戶將輸入多少信息。 這個賦值中不允許使用數組的向量和指針,還有其他方法可以解決嗎?

這是我的代碼

#include <iostream>
#include <windows.h>
#include <fstream>
using namespace std;

void ReadData (int[] , int);
int main()
{
    int product_code[9999];
    int code , num;
    ofstream outdata;
    ReadData (product_code , 9999);

    outdata.open("productlist.txt");
    cout << "How many product code?";
    cin >> num;
    for(int i=0 ; i<num ; i++)
    {
        cout << "Product Code : ";
        cin >> code;
    }
    outdata.close();

    for(int i=0 ; i<9999 ; i++)
    {
        cout << product_code[i] << endl;
    } 
    system("pause");
    return 0;       
}  

void ReadData(int p_code[] , int j)
{
    ifstream indata;
    indata.open("productlist.txt");
    while (indata >> p_code[j])
    {
        j++;
    }
    indata.close();
}

如果使用我的代碼並且用戶輸入的數據是 3, 1111, 2222, 3333 output 將是 1111 2222 3333 0 0 0 0 0 0 0 0 0 0.............

為什么你要運行 9999 次循環? 當您詢問用戶要輸入多少個產品代碼時? 一直運行到< num

for(int i=0 ; i < num ; i++)
    {
        cout << product_code[i] << endl;
    }

system("pause");

如果您不確切知道可以從文件或其他輸入中讀取的數據大小,請使用std::vector 它是一種動態擴展的數據結構,具有易於使用的接口,並在堆上分配。 不要為此目的使用 static 陣列。 您在堆棧上為 9999 個整數分配了 memory,並且許多數組項可能未使用。 此外,在這種情況下,您應該將已讀項目的計數分開。

它真的很容易使用。

std::vector<int> product_code;
ReadData (product_code);
...

void ReadData(std::vector<int>& p_code)
{
    ifstream indata;
    indata.open("productlist.txt");
    int value{0}
    while (indata >> value)
    {
        p_code.push_back(value);
    }
    indata.close();
}

填寫product_code后,您可以得到它的大小:

product_code.size();

並且可以通過索引訪問任何項目:

for(size_t idx = 0; idx < product_code.size(); ++idx)
{
    std::cout << product_code[idx] << std::endl;
}

或通過基於范圍的:

for(int value : product_code)
{
    std::cout << value << std::endl;
}

首先,您的代碼存在嚴重缺陷,即“ReadData (product_code, 9999);” 將溢出 product_code 數組。

您需要使用動態分配,因為您的程序在從文件中加載所有“產品代碼”之前不知道“產品代碼”的數量。 更好的是,使用 std::vector 作為這個標准 class 已經實現了所有你必須重新發明的東西。

暫無
暫無

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

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