【问题标题】:reading data from files and store them in vector<vector<pair<int,int>>> in c++从文件中读取数据并将它们存储在 C++ 中的 vector<vector<pair<int,int>>> 中
【发布时间】:2021-10-06 04:21:23
【问题描述】:

我有一个文件说data.txt,其中的数据如下所示;

1   80,982 163,8164
2   42,1689 127,9365 5,8026
3   57,1239 101,3381 43,731 115,7827 17,7002 72,794 150,4539
4   162,3924 70,5285 195,2490 72,6508 126,2625 121,7639 31,399 118,3626 90,9446 127,6808

我有一个容器vector&lt;vector&lt;pair&lt;int,int&gt;&gt;&gt;Graph(100), 通过阅读上述数据,我想以Graph[1].push_back({80,982})Graph[1].push_back({163,864}) 的身份执行操作。

类似地Graph[2].push_back({42,1689})Graph[2].push_back({127,9365})Graph[2].push_back({5,8026})。 第三行以此类推,直到结束。我不知道我可以使用ifstream file("data.txt");,然后获取一个字符串变量string str并以这种方式继续。

 while (getline(file, str)) {
        //perform operation
        // stringstream ss(str) can be used to parse commas
        //how to deal with variable length.
    }

请帮助我如何完成上述任务。非常感谢。

【问题讨论】:

  • 你有两个问题。第一个是解析用逗号分隔的数字。第二个是读取可变长度的行。您以前尝试过其中任何一种吗?
  • 我知道解析由任何分隔符分隔的数字,但在可变长度方面寻求帮助。

标签: c++ string algorithm data-structures stl


【解决方案1】:

要读取可变长度的行,您必须一次读取整行,然后解析它。

要阅读整行,请使用getline

string str;
getline(cin, str);

(这是getline 的几个变体之一。)

然后解析它,你可以遍历它,寻找空格和逗号,并将数字转换为数字,但这非常乏味。 C++允许使用stringstream,这样更简单:

#include <sstream>

std::stringstream ss;
ss << str;

int n=0;
string word;
while(ss >> word)
  cout << ++n << " " << word << endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多