首页 文章

用2个分隔符分隔输入文件

提问于
浏览
-3

我必须读取一个文件,其中行中的第一个字符是对象的名称,第二个字符(由空格分隔)是该对象的数据 .

我想知道如何将(在C中)每个数据片段逐个读入不同的向量 .

1 回答

  • 0

    你很幸运,我在代码写作心情......

    逐行获取字符串:

    std::ifstream file(path);
    if(file) // opened successfully?
    {
        std::string line;
        while(std::getline(file, line))
        {
            // use line
        }
        if(file.eof())
        {
            // entire file read, file was OK
        }
        else
        {
            // some error occured! need appropriate handling
        }
    }
    

    拆分字符串:

    std::string s   = "hello   world";
    auto keyEnd     = std::find_if(s.begin(), s.end(), isspace);
    auto valueBegin = std::find_if(i, s.end(), isalnum);
    
    std::string key(s.begin(), keyEnd);
    std::string value(valueBegin, s.end());
    

    您现在可以检查有效格式的键和值,例如: G . 两者都只包含一个字符,如果无效则拒绝该文件...

    两个向量?你可以 push_back 键和值,但也许 std::map<std::string, std::string> (或 std::unordered_map )是更好的选择?甚至 std::vector<std::pair<std::string, std::string>> ?所有这些都具有以下优点:它们将键和值保持在一起并且更加适合,除非您打算独立地维护两者(例如,在值可能/将保持原始顺序时对键进行排序) .

相关问题