C++动态数组和文件读取不能一起工作

标签 c++ arrays memory file-io compiler-construction

这样的代码:

int _tmain(int argc, _TCHAR* argv[])
{
    int *test = new int[];
    ifstream f("ofile.txt");
    for (int i=0,v; i<10; i++)
    {
        f>>v;
        test[i]=1; 
        cout<<"\nv = "<<v<<", i = "<<i<<endl;
    }

    return 0;
}

编译后出现此信息的原因:

enter image description here

我想(如果我错了请纠正我)这是关于内存的一些错误,但我不知道细节。如果我删除其中之一(文件读取或数组)它会起作用。 因此,很高兴听到对问题的解释。

最佳答案

你在想java。要分配这样的数组,您需要给出一个大小。 例如

    int *test = new int[20];

然而,更好的方案是使用整数 vector 。

    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <algorithm>  // for sort()

    int main(int argc, char *argv[])
    {
        std::vector<int> data;
        std::ifstream fsin("ofile.txt");

        int count = 0;
        while (fsin.good())
        {
            int v;
            fsin >> v;
            if (fsin.good())
            {
                data.push_back(v);
                std::cout << "\nv = " << v << ", i = " << count++ << std::endl;
            }
        }

        std::sort(data.begin(), data.end());

        for (size_t i=0; i<data.size(); i++)
            std::cout << i << '\t' << data[i] << std::endl;

        return 0;
    }

关于C++动态数组和文件读取不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824890/

相关文章:

c++ - 将控制台输出镜像到 C++ 文件

c++ - 对 boost::system 的 undefined reference

c# - 对象与对象[]

android - Android 中正确使用自定义字体

c++ - 如何在大型 C++ 程序中为所有 double 类型的数字设置小数精度

c++ - 我可以根据模板参数将某个值传递给成员构造函数吗?

C tiny,预分配数组不会溢出

java - Java 中的多维数组。有那么复杂吗?

python - Numpy 融合乘法和加法以避免浪费内存

c - 如何将 8 位数组写入 1/2 大小的 16 位数组