【问题标题】:How to limit the size of loop for unknown array size如何限制未知数组大小的循环大小
【发布时间】: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
  • 使用std::vector
  • 您也可以参考此链接了解更多详情variable length array
  • 不是显而易见的答案“使用 num 而不是 9999”吗?

标签: c++ arrays fstream


【解决方案1】:

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

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

system("pause");

【讨论】:

  • 可能,值得添加该程序应检查 num 与数组大小。 (根据我的经验,用户的定义是坏的。)而且,关于magic numbers 的提示也不会受到伤害。 ;-)
【解决方案2】:

如果您不确切知道可以从文件或其他输入中读取的数据大小,请使用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;
}

【讨论】:

  • 如果ifstream通过std::copy进入文件,你可以读取内容,它需要1行。
【解决方案3】:

首先,您的代码存在严重缺陷,即“ReadData (product_code, 9999);”将溢出 product_code 数组。

您需要使用动态分配,因为您的程序不知道“产品代码”的数量,直到它从文件中加载所有这些。更好的是,使用 std::vector 因为这个标准类已经实现了所有你必须重新发明的东西。

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多