微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将基于文本的列数据存储到数组 C++

如何解决将基于文本的列数据存储到数组 C++

我正在尝试将文本文件中的数据存储到数组中,以便以后使用。问题是当每条数据都有标题时,如何跳过文本中间的一行或单独取?

#include <iostream>
#include <fstream>



main() {
    double tab[100][6] = {0};
    int  i =0,j;
   std::string name = "test.txt";
//   std::cout << "Enter filename: ";
//   std::cin >> name;

   std::fstream file;
   std::string word;
   file.open(name.c_str());
   std::getline(file,word); // skip the first line
   while(file >> word) { //take word and print
      std::cout << word << std::endl;
      for(int j=0; j<=5; j++){
      tab[i][j] = stoi(word);
      }
      i++;
   }
   file.close();
   // displaying
   for(int j = 0; j<= 40;j++){
    std::cout << tab[i][0] << "\t" <<  tab[i][1] << "\t" << tab[i][2] << "\t" << tab[i][3] << "\t" << tab[i][4] << "\t" << tab[i][5];
   }
}

test.txt 文件

18407022  2018-07-05 00:04:02  MHAM  EIDW  42  S1REB  RYR5GW  3726  JNEIE  837B  Datum  RYR  IFR  Undefined  1  1  2018-07-05  00:15:38  2018-07-05  00:22:56  111  extended
0.0  113416.9  479798.5  -0.2  3.6  0.0
4.0  113395.2  479785.0  1.2  9.3  25.5
8.0  113352.2  479758.7  1.2  16.0  75.9
12.0  113284.9  479717.4  0.5  23.6  154.9
16.0  113189.9  479659.1  -0.5  32.2  266.3
20.0  113064.3  479582.1  -0.9  41.7  413.7
24.0  112904.9  479483.9  -0.3  52.1  600.9
18407022  2018-07-05  00:12:14  MHAM  EIDW  42  S1REB  RYR5GW  3726  JNEIE  837B  Datum  RYR  IFR  Undefined  1  1  2018-07-05  00:30:38  2018-07-05  00:42:56  111  extended
0.0  145431.6  480046.3  4533.3  180.4  0.0
4.0  144747.1  480268.2  4493.4  179.5  719.5
8.0  144059.0  480468.7  4452.0  179.0  1436.2
12.0  143368.6  480655.3  4409.8  178.7  2151.4
16.0  142677.0  480835.6  4367.6  178.6  2866.1
20.0  141985.8  481017.2  4326.1  178.8  3580.9
24.0  141295.9  481207.3  4286.1  179.0  4296.4

解决方法

如果有字母 (a-zA-Z),也许你先看看完整的一行?!

#include <regex>

...
std::regex e("a-zA-Z");

while(file >> word) { //take word and print
  
  if ( std::regex_match ( word,e))
    continue;
...
,

您可以尝试通过在每个标题的开头放置一个 # 来将文本文件中的每个标题标记为注释。

现在像这样读取文本文件:

#include<sstream>
...

...
std::ifstream file {"test.txt"};
std::string line;
std::istringstream iss;
double tab[100][6];
int i=0,j;
...

while (getline(file,line))
{
  if (!(line[0]=='#'))
  {
    iss.str(line);

    for (j=0; j<6; ++j)
      iss >> tab[i][j];
    
    iss.clear();

    ++i;
  }
}

file.close();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。