我遇到了一个我不知道数组大小的问题,当我需要在数组中提示信息时,我不知道如何限制循环的大小,以便仅提示数组中的内容,并且退出循环。最初,我为数组索引声明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输出将是1111222233330000000000..........
为什么要运行9999次循环?当您问用户要输入多少个产品代码时?一直运行到< num
for(int i=0 ; i < num ; i++)
{
cout << product_code[i] << endl;
}
system("pause");