Timʘtei Timʘtei -4 years ago 70
C++ Question

strange array reading from file in C++

I was trying to initialize an array of

element in
like this:
int array[1000001]
. I have 4GB of RAM so I guessed the problem is that my laptop can't hold a so big array because of it's
4 * 1000001 bytes
size. So I decided to try to make it
(just because I wanted to know if my guess was right). I am reading the array from a file. This is my code:

#include <iostream>
#include <fstream>
#include <climits>

using namespace std;

int main()
fstream in("C:\\Users\\HP\\Documents\\Visual Studio 2017\\Projects\\inputFile.in");
if (!in)
cerr << "Can't open input file\n";
return 1;
fstream out("outputFile.out", fstream::out);
if (!out)
cerr << "Can't open output file\n";
return 1;

int n;
in >> n;
int i;
char array[100];
for (i = 0; i < n; i++)
in >> array[i];


For input:

45 5 4 3 12

my array is
{4, 5, 5, 4, 3}

For input:
12 3 4 5 45

my array is
{1, 2, 3, 4, 5}

Now I am really confused. Why is this happening?

Answer Source

In this statement

in >> array[i];

there is used the operator

template<class charT, class traits>
basic_istream<charT, traits>& operator>>(basic_istream<charT, traits>&, charT&);

where the template parameter charT is substituted for template type argument char.

The operator reads one character from the stream skipping white space characters.

So as the stream contains the following sequence of characters

45 5 4 3 12

then for the five calls of the operator there will be read the following characters

4, 5, 5, 4, 3

white space characters will be skipped.

You could read the stream as having integers for example like

for (i = 0; i < n; i++)
    int value;
    in >> value;
    array[i] = value;

As for the problem with the large integer array when you should declare it as having the static storage duration for example declare it outside any function. Or you could use standard class std::vector instead of the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download