【问题标题】:C++ file input with mixed delimiters and data types具有混合分隔符和数据类型的 C++ 文件输入
【发布时间】:2015-04-14 23:28:03
【问题描述】:

我正在尝试从文本文件中输入数据: 行格式如下... 字符串|字符串|int double

示例: 鲍勃|橙子|10 .89

我可以使用 Getline(infile, line)

我不明白如何将行拆分为字符串变量中的不同变量。

谢谢

【问题讨论】:

标签: c++ io


【解决方案1】:

首先,您可以使用 strchr 编写一些不错的老式 c 代码。

如果您使用的是 std::String,则使用 string.find / find_first_of

http://www.cplusplus.com/reference/string/string/find_first_of/

【讨论】:

    【解决方案2】:

    您将此标记为 C++。所以也许你应该尝试使用格式化的提取器......

    这是一个“ram”文件(就像磁盘文件一样工作)

    std::stringstream ss("Bob|oranges|10 .89");
    //               this ^^^^^^^^^^^^^^^^^^ puts one line in file
    

    我会对两个字符串使用 getline,并带有小节终止符

    do {
       std::string cust;
       (void)std::getline(ss, cust, '|'); // read to 1st bar
    
       std::string fruit;
       (void)std::getline(ss, fruit, '|'); // read to 2nd bar
    

    然后直接读取int和float:

       int count = 0;
       float cost;
       ss >> count >> cost;  // the space char is ignored by formatted extraction
    
       std::cout  << "\ncust: " << cust << "\n"
                  << "      " << count << "  " << fruit
                 << " at $"   << cost
                 << " Totals: "  << (float(count) * cost)  << std::endl;
    
       if(ss.eof())  break;
    
    }while(0);
    

    如果要处理更多的行,则需要找到eoln,并为上述样式的每条记录重复。

    这种方法非常脆弱(格式的任何更改都会强制更改您的代码)。

    这只是为了让您开始。根据我的经验,使用 std::string find 和 rfind 的脆弱性要小得多。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 2021-07-13
      • 2019-04-01
      • 2017-10-04
      • 1970-01-01
      • 2013-04-08
      • 2012-03-04
      • 2021-12-15
      • 2017-04-28
      相关资源
      最近更新 更多