c++ - 从 C++ 文件中读取,处理空白

标签 c++ string file integer ifstream

我想从 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/

相关文章:

c++ - 如何在构造函数的成员初始化列表中调用两个函数?

c++ - 确定可以分解为质数 {2,3,5,7} 的下一个最高数

c++ - 哪个是更好的方法 - 将 `const reference` 与 `boost::shared_ptr<Class>` 存储为成员变量

java - 比较两个长字符串

file - 如何将 2 个视频文件和音频文件与 FFMPEG 结合起来?

c++ - 类之间的信息丢失

css - 将字符串解析为 SASS 中的映射

C++ 和 UTF8 - 为什么不直接替换 ASCII?

linux - Nmap 找不到保存的文本文件

javascript - csv 文件的 d3 检索在 javascript 控制台中返回 Nan