c++ - 如何在 C++ 中解析数字表

标签 c++ parsing numbers text-files tabular

我需要解析一个格式为 ascii 文本的数字表。每行文本有 36 个空格分隔的有符号整数,文件中有大约 3000 行。输入文件是我在 Matlab 中生成的,因此我可以修改格式。另一方面,我也希望能够在 VHDL 中解析相同的文件,因此 ascii 文本是唯一可能的格式。

到目前为止,我有一个像这样的小程序可以循环遍历输入文件的所有行。我只是还没有找到一种方法来摆脱个人数字。我不是 C++ 最纯粹的人。我会考虑 fscanf() 但 36 个数字有点多了。请提出从文本文件中获取数字的实用方法。

int main()
{
    string line;
    ifstream myfile("CorrOut.dat");
    if (!myfile.is_open())
        cout << "Unable to open file";
    else{
        while (getline(myfile, line))
        {
            cout << line << '\n';
        }
        myfile.close();
    }
    return 0;
}

最佳答案

使用 std::istringstream。这是一个例子:

#include <sstream>
#include <string>
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    string line;
    istringstream strm;
    int num;
    ifstream ifs("YourData");
    while (getline(ifs, line))
    {
        istringstream strm(line);
        while ( strm >> num )
           cout << num << " ";
        cout << "\n";
    }
}

Live Example

如果要创建表,请使用 std::vector 或其他合适的容器:

#include <sstream>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    string line;

    // our 2 dimensional table
    vector<vector<int>> table;

    istringstream strm;
    int num;
    ifstream ifs("YourData");
    while (getline(ifs, line))
    {
        vector<int> vInt;
        istringstream strm(line);
        while ( strm >> num )
           vInt.push_back(num);
        table.push_back(vInt);
    }
}

table vector 逐行填充。请注意,我们创建了一个中间 vector 来存储每一行​​,然后该行被添加到表中。

Live Example

关于c++ - 如何在 C++ 中解析数字表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30955377/

相关文章:

c++ - Cmake : Copy in library file if not present

linux - 如何从文件中提取特定字符串(linux)

python - 使用 minidom 进行 XHTML 解析

javascript - 在 JavaScript 中将字符串转换为十进制数

c# - 在数字中插入 1 位 C#

mysql - 在 Mysql 中选择 Something + 任意数字

c++ - 多重继承来自多重继承

c++ - 推导(非)模板类型的签名

c++ - 使用模板实现通用过滤器

javascript - 在javascript中解析字符串