c++ - 如何限制未知数组大小的循环大小
问题描述
遇到一个不知道数组大小的问题,当需要提示数组中的信息时,不知道如何限制循环的大小,只提示数组中的内容并退出环形。最初,我为数组索引声明 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");
推荐阅读
- haskell - 链接类型类、类和实例
- python - 使用索引查找和打印特定单词
- python - 如何使用 Pybuilder 将包上传和下载到本地 pypi
- reactjs - 编码空格时反应不一致
- performance - IndexedDB 数据库备份/恢复场景
- git - 如何防止git覆盖.CSPROJ等文件?
- html - 如何将 Bootstrap 用于定位、分层和响应式 Div
- r - 如何使 Markdown 模板/Latex 包适应 R-Markdown?
- javascript - 使用 Object.values() 后创建新对象的更简洁方法?
- mongodb - 聚合和搜索嵌套文档