I am using the following code to read a text file;
void load_triplet(const std::string filename,
std::vector<int> &rows,
std::vector<int> &cols,
std::vector<double> &data)
{
int a;
int b;
double c;
const unsigned int MAXBUFF = 1000000;
rows.reserve(MAXBUFF);
cols.reserve(MAXBUFF);
data.reserve(MAXBUFF);
std::ifstream file;
file.open(filename, std::ios::in);
if (file.is_open())
{
int counter = 0;
while (!file.eof())
{
file >> a >> b >> c;
rows.push_back(a);
cols.push_back(b);
data.push_back(c);
}
file.close();
}
else
{
std::cout << "Error reading triplet " << filename << "\n";
exit(EXIT_FAILURE);
}
}
Input has 11 rows and last line is empty (11 rows data and an empty line);
load_triplet("A.txt", rows, cols, data);
for (int i = 0; i < rows.size(); ++i)
cout << i << " " << rows[i] << " " << cols[i] << " " << data[i] << endl;
int n = rows.size();
cout << "size of rows : " << n << endl;
cout << "rows[11] is " << rows[11] << endl;
My output from code is:
0 0 0 1
1 0 2 -3e+09
2 1 1 1
3 1 3 -2e+09
4 2 2 1
5 2 5 -0.00111111
6 3 3 1
7 3 4 -0.000833333
8 4 4 1
9 4 5 -3
10 5 5 1
11 5 5 1
size of rows : 12
rows[11] is 5
I have also find this questions about skipping empty lines, but I don't know how to combine them with this to read different type so I made a new question.