【发布时间】:2019-11-14 09:09:45
【问题描述】:
遇到一个不知道数组大小的问题,当需要提示数组中的信息时,不知道如何限制循环的大小,只提示数组中有什么并退出循环。最初,我为数组索引声明 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++时了解std::vectors
-
您也可以参考此链接了解更多详情variable length array
-
不是显而易见的答案“使用 num 而不是 9999”吗?