Reputation: 3
I'm fairly new to C++ and I need some help. The input is a text file that looks something like that:
5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
In the first line there is an integer N and then there are N lines with N numbers. How can I read the file and create a table (a 2d array)? Like that: [ [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], ].
That's my code right now:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string fname;
cout << "Enter the file name" << endl;
cin >> fname;
ifstream MyReadFile(fname);
string myText;
int N;
int i = 0;
while (getline(MyReadFile, myText))
{
if (i == 0)
{
N = stoi(myText);
}
i += 1;
}
MyReadFile.close();
}
I know it looks bad, I've been learning C++ for only a week. Thanks in advance.
Upvotes: 0
Views: 318
Reputation: 4263
You don't need explicitely convert string to text via stoi. istream::operator>>
does that for you:
ifstream in(filename);
int n;
in >> n;
vector<vector<int>> v(n, vector<int>(n));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
in >> v[i][j];
Upvotes: 4