c++ - 如何解析这些未知大小的数据

标签 c++ c

我有一个简单的文本文件,每行包含说明。例如

A 1 1
B 2 1 A
C 3 1 A
D 4 1 B C

基本语法是 Letter、Num、Num、Letter(s)

我只是不知道应该调用什么函数来解析数据,以及如何用给定的语法解析它。我觉得有很多方法可以做到这一点。

最佳答案

下面的 C++ 示例展示了从文件中读取单个字符的一种可能方法,控制行尾:

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;

int main(void)
{
    ifstream inpFile("test.txt");
    string str;
    char c;
    while (inpFile.good()) {
        // read line from file
        getline(inpFile, str);
        // make string stream for reading small pieces of data
        istringstream is(str);
        // read data ingnoring spaces
        do
        {
            is >> c; // read a single character
            if (!is.eof()) // after successful reading
                cout << c << " "; // output this character
        } while (is.good()); // control the stream state
        cout << "[End of line]" << endl;
    }
    cout << "[End of file]" << endl;
}

这里istringstream用于处理getline获取到的单行。

读取带有 is >> c 的字符后,可以检查 c 中的值,例如:

        if (!is.eof()) // after successful reading
        {
            // analyze the content
            if ( isdigit(c) )
                cout << (c - '0') << "(number) "; // output as a digit
            else
                cout << c << "(char) "; // output as a non-number
        }

注意:如果文件不能包含单个字符/数字,而是数字和单词,则 c 类型应该合适(例如 string)

关于c++ - 如何解析这些未知大小的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39716089/

相关文章:

c - 我如何始终包含静态库中的符号?

c++ - 如何锁定队列变量地址而不是使用临界区?

c - 如何将 PEM 证书作为 i2d_X509 的第一个参数传递

c++ - 三十部分库中的线程安全

c++ - 如何在 C/C++ 上创建和保存 .docx 文档?

c++ - 插入或更新 map

char 字符串使我的 while 循环退出?

c++ - std::cin 缓冲区是否有大小限制?

c++ - wxComboBox 返回十六进制

c++ - Cuda 推力字符串或字符排序