How to allocate ONE D ARRAY AT RUNTIME

I have an text file which contain integers value.
I have made the code to read the file but i am not able to dynamically allocate array and store the value in the array.The file may sometime contain 50 value and sometime contain 300 value.
The file may also contain the value that are repeating integers for example the file may be as follows:-
1,2,3,1,1,1,1,2,2,2,21,5,5,5,5,5,5,4,5,45,4,54,544,
I want the value to be stored in array only once and allocate array at runtime.Please help me to do this by telling sample code.

1
2
3
4
5
6
int* array = new int[numberOfValues];

for (int i=0; i<numberOfValues; ++i)
{
  inputFile >> array [i];
}
Thanks for the reply sir but suppose i enter int numberOfValues=50 and values are 220 then my program will fail then what to do?
This is actually a very simple problem and you should be able to work it out for yourself. How can you examine the file to discover how many values are in it? You could open it and start reading the values, and when there are no more values to read, you know how many there are in that file.

An alternative is to just use a proper C++ container that takes care of its own size.
Last edited on
Since the OP actually requested that no two values should repeat, an std::set is pretty obvious:
http://www.cplusplus.com/reference/stl/set/
> The file may also contain the value that are repeating integers for example the file may be as follows:-
> 1,2,3,1,1,1,1,2,2,2,21,5,5,5,5,5,5,4,5,45,4,54,544,
> I want the value to be stored in array only once and allocate array at runtime.

Is there a reason for not using the standard C++ library?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <vector>
#include <fstream>
#include <algorithm>

std::vector<int> read_unique_integers( const char* path2file, char delimiter = ',' )
{
    std::ifstream file(path2file) ;
    std::vector<int> seq ;
    int value ;
    char delim ;
    while( ( file >> value >> delim ) && ( delim == delimiter ) ) seq.push_back(value) ;
    std::sort( seq.begin(), seq.end() ) ;
    seq.erase( std::unique( seq.begin(), seq.end() ), seq.end() ) ;
    return seq ;
}


http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm
http://en.cppreference.com/w/cpp/algorithm/sort
http://en.cppreference.com/w/cpp/algorithm/unique
@Tarun Batra
Do you know the range of the values that is the minimum and maximum values that can be stored in the file? For example 0-500 or 0-1000?
If you know apriori the range of values you can use std::bitset.:)
Topic archived. No new replies allowed.