I am trying to read a 12 digit number from a text file in to an array. I have been able to do this successfully if I place whitespace between each digit. for instance:
1 1 1 1 1 1 1 1 1 1 1 1
But when I remove the whitespace between the digits my program is no longer able to allocate the array from the text file. for instance:
111111111111
I am sure the answer is simple but I have been unable to find the solution to my exact problem anywhere. Below is my while loop that I use to allocate the array.
void int_class::allocate_array(std::ifstream& in, const char* file)
{
//open file
in.open(file);
//read file in to array
int i = 0;
while( !in.eof())
{
in >> myarray[i];
i++;
}
in.close();
}
To read an array of chars, supposing there are no spaces or other delimiters, you can read the whole of it from input stream at once:
in >> myarray;
To create an array of integers, you can read the input char by char and fill the array in place:
char c;
int i = 0;
while( !in.eof())
{
in >> c;
myarray[ i++ ] = c - '0';
}
In this case there may be any quantity of spaces in any place, they will be ignored.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.