Reputation: 1
I am trying to read integers from a text file and put them into a dynamic array that will be represented as vectors and matrices for an assigment.
An example of a few lines from the input file:
3#456
33#123456789
The numbers before the pound sign represent the elements of the vector or matrix, so 3# would mean a three element vector and 33# would mean a matrix with 3 rows and 3 columns.
Reading those isn't really a problem as we were told we can assume we know which lines are matrices and which are vectors, however, I have never working with C++ file I/O so I don't know how to iterate through the numbers 4,5,6 and put them into a 3, 9, 12, etc, element dynamically created array. Here's somewhat of a sample of what I'm working with.
int *a;
int size_a;
char x;
ifstream infile("input.txt");
if (infile.is_open())
{
infile >> size_a;
// The x is basically a junk variable used to go past the '#'
// when reading the file
infile >> x;
a = new int[size_a];
}
After that, I have no real idea of how to loop until the end of the line and put the remaining elements in the array. For example in this line, the numbers 4, 5, and 6 would need to be put into the a array, then break from adding elements and go to the next line to work on the next array, which I don't know how to do either. Any ideas?
Upvotes: 0
Views: 2448
Reputation: 4452
The below code will do this for you. Note that you do not need to use new
here - you should just use a std::vector. In that case, the number before the '#' is unneeded as you do not need to specify the size of the array when you create it.
For that reason I have used new
here anyway to show you how to read both parts of the file.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream file("input.txt");
if(file.good()) {
std::string line;
std::getline(file, line);
std::string::size_type pos = line.find('#');
std::string strSize = line.substr(0, pos);
std::string strValues = line.substr(pos + 1);
int size = 0;
for(char c : strSize) {
if(size == 0)
size = static_cast<int>(c - '0');
else
size *= static_cast<int>(c - '0');
}
int* values = new int[size];
for(int i = 0; i < size; ++i) {
values[i] = static_cast<int>(strValues[i] - '0');
}
std::cout << "Array of size " << size << " has the following values:" << std::endl;
for(int i = 0; i < size; ++i) {
std::cout << values[i] << std::endl;
}
delete[] values;
}
}
Upvotes: 2