首页 > 解决方案 > 如何限制未知数组大小的循环大小

问题描述

遇到一个不知道数组大小的问题,当需要提示数组中的信息时,不知道如何限制循环的大小,只提示数组中的内容并退出环形。最初,我为数组索引声明 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 ....

标签: c++arraysfstream

解决方案


为什么你要运行 9999 次循环?当您询问用户要输入多少个产品代码时?只跑到< num

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

system("pause");

推荐阅读