如何限制未知数组大小的循环大小

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 输出将是 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。它是一个动态扩展的数据结构,具有易于使用的接口,并且分配在堆上。 不要为此目的使用静态数组。您在堆栈上为 9999 个整数分配了内存,并且许多数组项可能未被使用。此外,在这种情况下,您应该将阅读项目的数量分开。

真的好用

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:

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

首先,您的代码存在严重缺陷,因为 "ReadData (product_code , 9999);" 会溢出 product_code 数组。

你需要的是使用动态分配,因为你的程序在从文件中加载所有这些之前不知道 "product codes" 的数量。更好的是,使用 std::vector 因为这个标准 class 已经实现了所有你必须重新发明的东西。