c ++ ifstream函数和字段分隔符 [英] c++ ifstream function and field separators

查看:935
本文介绍了c ++ ifstream函数和字段分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个程序,我只使用shell脚本中的数据文件的字段分隔符。但我试图使用标准库函数ifstream()从数据文件中读入。唯一的问题是我得到的数据像这样



A:KT5:14:这是一个哈希表,我需要分离数据结构以及事务类型的行中的值。我一直在寻找网络,没有发现太多的字段分隔符,我发现是很混乱。



问题是,有没有办法用ifstream函数设置字段分隔符,还是有另一个标准库i / o函数我应该使用? p>

感谢。

解决方案

getline 提供了指定分隔符的选项。然后,您可以按照由 _Delim 分隔的 string 序列从流中读取输入:

  template< class CharType,Class Traits,class Allocator> 
basic_istream< CharType,Traits>& getline(
basic_istream< CharType,Traits>& _Istr,
basic_string< CharType,Traits,Allocator>& _Str,
CharType_Delim
);

如果这是统一的结构化数据,定义一个结构体来包含它并实现 operator>> 使用上述函数内部的函数从流中加载每个实例。



必须处理多行(以便换行符是记录分隔符和:字段分隔符),使用 basic_istream将每行加载到 stringstream :getline ,然后将该行处理成如图所示的字段。


For this program i have only used field separators from data files in shell script. But I am trying to use the standard library function ifstream() to read in from a data file. The only problem is I am getting the data like so

A:KT5:14:executive desk:

This is for a hash table, and I need to separate the values in the line for the data structure as well as the transaction type. I’ve been looking around the web and have not found much on field separators and what I have found was quite confusing.

The question then being, is there a way to set a field separator with the ifstream function or is there another standard library i/o function I should be using?

Thanks.

解决方案

getline gives you the option to specify a delimiter. You can then read the input from a stream as a sequence of string separated by _Delim:

template<class CharType, class Traits, class Allocator>
   basic_istream< CharType, Traits >& getline(
       basic_istream< CharType, Traits >& _Istr,
       basic_string< CharType, Traits, Allocator >& _Str,
       CharType _Delim
   );

If this is uniformly structured data it might be useful to define a struct to contain it and implement operator>> to load each instance from the stream, using the above function internal to the operator code.

If you have to process multiple lines (so that newline is a record separator and : a field separator), load each line in turn into a stringstream using basic_istream::getline, and then postprocess the line into fields as shown.

这篇关于c ++ ifstream函数和字段分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆