0

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.

2
  • You didn't specify a size for you allocation! Commented Dec 29, 2013 at 11:57
  • i assume you also meant test[i]=v; not test[i]=1; Commented Dec 29, 2013 at 12:32

2 Answers 2

5

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;
    }
Sign up to request clarification or add additional context in comments.

4 Comments

The goal is to save the file (it contains numbers only in every string) content in array which may be re-sorted later. I guess your example will be convinient after a little changing. But I still can't assemble all this together. Plsss, point out how to do that.
@srgg6701 - hich part is unclear? Each time around the loop you read a value from the file into 'v', then append that value to the vector 'test'. You can then do whatever is required with the vector data.
Anybody, tell me - why there the condition if (fsin.good()) is repeated inside the loop while (it is already set)? Is it a mistake or it is really necessary?! I'm confused :(
The inner test confirms that "fin >> v" succeeded.
3

You have to allocate a fixed size array, int *test = new int[]; shouldn't even work.

If the size is known, use int *test = new int[size];, otherwise try using a std::vector or std:array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.