我有一个简单的文本文件,每行包含说明。例如
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/