C++具有混合分隔符和数据类型的文件输入

C++ file input with mixed delimiters and data types

本文关键字:数据类型 文件 输入 分隔符 混合 C++      更新时间:2023-10-16

我正在尝试从文本文件输入数据:行格式如下...字符串|字符串|整数双精度

例:鲍勃|橙子|10 .89

我可以使用获取行(文件,行)

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

谢谢

首先,您可以使用strchr编写一些很好的老式C代码。

或者使用 string.find/find_first_of 如果你使用的是 std::String

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

您将其标记为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 并直接浮点:

   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 要不那么脆弱。

祝你好运。