Issue
I want to read from a file containing an unknown list of 4 integers each. So each line of the file contain something like this"12.0 43.0 19.0 77.0" I thought of using a 2 dimensional array but I don't know the size of the file because its a very big file. I ended up reading each line as a string and used a "while(!in_file.eof())" so I can reach the end of the file but the problem is, I need to get the numbers individually form each line.
Solution
You don't need to know how many lines are in your file or how many numbers are in each line.
Use std::vector< std::vector< int > > to store data. If in each line, integers are separated with a space, you can iterate a string of integers and add them one by one to a vector:
#include <iostream>
#include <string>
#include <stream>
#include <vector>
using namespace std;
int main()
{
string textLine = "";
ifstream MyReadFile("filename.txt");
vector<vector<int>> main_vec;
// Use a while loop together with the getline() function to read the file line by line
while (getline(MyReadFile, textLine)) {
vector<int> temp_vec; // Holdes the numbers in a signle line
int number = 0;
for (int i = 0, SIZE = textLine.size(); i < SIZE; i++) {
if (isdigit(textLine[i])) {
number = number * 10 + (textLine[i] - '0');
}
else { // It's a space character. One number was found:
temp_vec.push_back(number);
number = 0; // reset for the next number
}
}
temp_vec.push_back(number); // Also add the last number of this line.
main_vec.push_back(temp_vec);
}
MyReadFile.close();
// Print Result:
for (const auto& line_iterator : main_vec) {
for (const auto& number_iterator : line_iterator) {
cout << number_iterator << " ";
}
cout << endl;
}
}
Hint: This code works for only integers. For floats, you can easily identify the indices of spaces in each line, get substring of your textLine, and then convert this substring to a float number .
Answered By - ArashV Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.