C++具有混合分隔符和数据类型的文件输入
C++ file input with mixed delimiters and data types
我正在尝试从文本文件输入数据:行格式如下...字符串|字符串|整数双精度
例:鲍勃|橙子|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 要不那么脆弱。
祝你好运。
相关文章:
- 使用 Boost.Spirit 解析具有混合数据类型的 OBJ 文件?
- 我的头文件 DNode 中的我的数据类型未被识别为数据类型
- 是否可以用类似C/C++(或任何语言)的语言,从作为用户输入的字符串或文件中创建用户定义的数据类型
- 如何将数据类型声明从.cpp文件传输到 .cu 文件
- 将多种数据类型写入文件时的其他行和额外的数组元素
- 在C 中按行读取文本文件,每行都是不同的数据类型
- 当拥有倍数数据类型C 时,正确读取文件末尾的方法
- 如何将自定义数据类型(用std::对填充的std::数组)写入文件流
- 如何在文件中读取不同的数据类型?C
- C 从具有不同数据类型的文件中循环
- 哪种数据类型用于存储文件名和文件大小的使用
- 如何通过读取文件将不同数据类型的数据推送到向量中
- C++ 从文本文件数据类型读取为结构,并将数据存储在列表的向量中
- 文件中数据类型的计数(以C++为单位)
- C++具有混合分隔符和数据类型的文件输入
- 头文件中异常的数据类型和 #include
- c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
- 分析位图文件时,如何替换WORD和DWORD数据类型
- RegGetValue返回的数据类型与admx文件中提到的gpo设置的数据类型不同
- 如何从文件中识别数据类型