简体   繁体   English

C ++将信息从文本文件加载到2D数组中

[英]C++ Loading information from text file into a 2D Array

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. 我需要使用存储在文本文件中的数据加载2D数组。 The text file reads as follows (Two numbers then the end of the line. ie 1 1949, then next line): 文本文件的内容如下(两个数字,然后是行的末尾。即1 1949,然后是下一行):


1 1949 1949年1月1日

2 1972 1972年2月2日

3 1983 1983年3月3日

4 1959 1959年4月4日

5 1987 1987年5月5日

6 1991 1991年6月6日

7 1995 1995年7月

8 1991 1991年8月8日

9 1957 1957年9月9日

10 1980 1980年10月10日

11 1995 1995年11月11日

12 1995 1995年12月12日


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; 在这里,我使用pair<int, int>来存储每一行​​; if you have C++11 you can use array<int, 2> instead. 如果您具有C ++ 11,则可以改用array<int, 2> 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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM