【问题标题】:Delimiting a input file by 2 delimiters用 2 个分隔符分隔输入文件
【发布时间】:2018-12-09 21:01:25
【问题描述】:

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

我想知道如何(在 C++ 中)将这些数据中的每一个一个一个地读入不同的向量中。

【问题讨论】:

  • 你试过什么?您尝试的minimal reproducible example 在哪里?你的尝试是如何奏效的,或者没有奏效?你能从你想阅读的文件中复制粘贴摘录吗?也许刷新how to ask good questions,以及this question checklist
  • std::ifstream in("in.txt"); in >> some_str;?
  • 如果一行只有两个字符,中间怎么会有空格分隔符?
  • 请提供文本文件内容的示例。
  • 此外,还有许多读取逗号分隔值 (csv) 格式的文本文件的示例,这些示例应该可以作为您使用的适当示例。尝试搜索 csv。大多数实现都允许您指定一个空格作为分隔符,而不是一个空格。

标签: c++ file input delimiter


【解决方案1】:

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

逐行获取字符串:

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>>?所有这些都具有将键和值保持在一起的优点,并且会更合适,除非您打算独立维护两者(例如,对键进行排序,而值可能/应该保持原始顺序)。

【讨论】: