I'm a very novice programmer and I've run into a bit of a problem. I need to load a 2D array with the data stored in a text file. The text file reads as follows (Two numbers then the end of the line. ie 1 1949, then next line):
1 1949
2 1972
3 1983
4 1959
5 1987
6 1991
7 1995
8 1991
9 1957
10 1980
11 1995
12 1995
The array should be formatted in the same fashion. Certainly not looking for an answer here, but a push in the right direction. I've been searching to no avail. Thank you.
Here I use pair<int, int>
to store each row; if you have C++11 you can use array<int, 2>
instead. The rest is boilerplate, reading and splitting lines.
#include <cassert>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
assert(argc == 2);
ifstream input(argv[1]);
assert(input);
vector<pair<int, int> > data;
for (string line; getline(input, line); )
{
istringstream stream(line);
data.resize(data.size() + 1);
stream >> data.back().first >> data.back().second;
}
}
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.