我想从 C++98 中的文本文件中读取数据。它有一个模式,但有时一个字段是空的:
ID Name Grade level
1 a 80 A
2 b B
3 c 90 A
如何从文件中读取以便忽略空白? (我希望我可以简单地使用正则表达式:\d*)
有什么简单的方法吗?
最佳答案
您需要使用您对输入的了解来对缺失的内容做出假设。您可以使用 std::stringstream
来解析文本行中的各个术语。换句话说,std::stringstream
通过忽略空格并仅获取完整术语来处理空白,例如 std::stringstream("aaa bbb") >> a >> b
将使用 "aaa"
加载字符串 a
和使用 "bbb"
加载 b
>.
这是一个解析输入的示例程序,从头开始构建一个健壮的解析器可能很困难,但是如果您的输入是严格的并且您确切地知道会发生什么,那么您可以使用一些简单的代码来摆脱困境:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
//-----------------------------------------------------------------------------
// holds a data entry
struct Entry {
int id;
std::string name;
int grade;
std::string level;
Entry() {
// default values, if they are missing.
id = 0;
name = "Unknown";
grade = 0;
level = "?";
}
void ParseFromStream( std::stringstream &line ) {
std::string s;
line >> s;
if( s[0] >= '0' && s[0] <= '9' ) {
// a number, this is the ID.
id = atoi( s.c_str() );
// get next term
if( line.eof() ) return;
line >> s;
}
if( s[0] >= 'a' && s[0] <= 'z' || s[0] >= 'A' && s[0] <= 'Z' ) {
// a letter, this is the name
name = s;
// get next term
if( line.eof() ) return;
line >> s;
}
if( s[0] >= '0' && s[0] <= '9' ) {
// a number, this is the grade
grade = atoi( s.c_str() );
// get next term
if( line.eof() ) return;
line >> s;
}
// last term, must be level
level = s;
}
};
//-----------------------------------------------------------------------------
int main(void)
{
std::ifstream input( "test.txt" );
std::string line;
std::getline( input, line ); // (ignore text header)
while( !input.eof() ) {
Entry entry;
std::getline( input, line ); // skip header
if( line == "" ) continue; // skip empty lines.
entry.ParseFromStream( std::stringstream( line ));
std::cout << entry.id << ' ' << entry.name << ' ' <<
entry.grade << ' ' << entry.level << std::endl;
}
return 0;
}
关于c++ - 从 C++ 文件中读取,处理空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27239234/