This is allowed as an extension by some compilers, but is not strictly part of C++.
int Hello[n];
As an alternative, you can allocate the memory yourself:
int* Hello = new int[n];
And free it yourself also:
delete[] Hello;
But you can avoid manual memory management by usng std::vector
from <vector>
. One of its constructors accepts an initial size:
vector<int> Hello(n); // Vector with n elements, all initially 0.
You can also set an initial capacity without resizing, to do the allocation once:
vector<int> Hello; // Empty vector.
Hello.reserve(n); // Allocate space for n elements; size() is still 0.
Then read into an int
and use push_back
to insert values:
int value;
while (input >> value)
Hello.push_back(value);
Note the use of input >> value
as the loop condition—this reads as long as reads are successful. eof()
returns true only when the last read operation failed due to unexpected end of file, which is unlikely to be exactly what you want.