Search code examples
c++arraysmemoryfile-io

C++ the dynamic array and file reading don't work together


Such a code:

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;
}

caused of this message after compiling:

enter image description here

I guess (correct me if I'm wrong) here is some error about memory, but details are unknown for me. If I remove one of them (file reading or array) it works. So it will be great to hear an explanation of the problem.


Solution

  • You're thinking java. To allocate an array like that you need to give a size. e.g.

        int *test = new int[20];
    

    However a better scheme would be to use a vector of integers.

        #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;
        }