我们可以更改字符串流对象的重载运算符">>"默认行为吗?
Can we change the default behavior of ">>" overloaded operator for stringstream object?
我的需求描述如下。我正在读取包含
的stringstream对象中的文件"NECK_AP
UL, 217.061, -40.782n
UR, 295.625, -40.782n
LL, 217.061, 39.194n
LR, 295.625, 39.194".
当我试图在变量中填充值时,我得到","也伴随着它。有没有人建议我可以将所有这些值存储在各自的变量中,而不使用","
只是一个示例代码来帮助解决这个问题:
int _tmain(int argc, _TCHAR* argv[])
{
char pause;
stringstream stream;
stream.str("NECK_AP
UL, 217.061, -40.782n
UR, 295.625, -40.782n
LL, 217.061, 39.194n
LR, 295.625, 39.194");
string value1,value2,value3,value4;
stream >> value1>>value2>>value3>>value4;
cout << value1<<value2<<value3<<value4<<endl;
cin >> pause;
return 0;
}
<标题> 输出NECT_AP UL, 217.061, -40.782
<标题>要求输出NECT_AP UL 217.061 -40.782
标题>标题>您需要理解(大多数时候)编写函数(或操作符等)是为了完成某些特定的工作。操作符>>具有从流到某个地方获取数据的工作。这是它的工作,应该是这样。你要做的,是写一个新的函数(或使用现有的),稍后将改变值,你想要的方式。
在标准库的帮助下,你可以很容易地完成你想做的事情:
#include <algorithm>
//some code...
std::replace_if(value1.begin(), value1.end(), [](char x){return x == ',';}, ' ');
对每个值执行此操作。或者,将所有内容加载到一个字符串中,在这个字符串上使用这个函数,并打印其内容。它是做什么的?replace_if接受四个参数:容器的开始和结束迭代器(前两个参数),一些谓词函数(我使用所谓的lambda表达式,或匿名函数;但是您可以编写单独的函数并提供它的名称(没有问题!)和新值。基本上,它可以翻译为"如果满足谓词(换句话说,是冒号),将字符串中的每个字符替换为' '"。
你可以这样做。operator>>
(std::string
)跳过空白字符,然后将字符读入所提供的变量,直到到达另一个空白字符。
流有一个相关的区域设置,用于确定哪些字符是"空白"或不被视为"空白"。我们可以编写自己的区域设置,将,
分类为'空白',告诉流使用该区域设置,并根据需要读取我们的数据。
为简单起见,我编写了一些代码,将所有字符串读入vector,然后在其单独的行中显示它读入的每个字符串,因此很容易看到它读入每个字符串的确切内容。
#include <locale>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <iostream>
struct reader: std::ctype<char> {
reader(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table() {
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size,std::ctype_base::mask());
rc[','] = std::ctype_base::space;
rc['n'] = std::ctype_base::space;
rc[' '] = std::ctype_base::space;
return &rc[0];
}
};
int main() {
std::istringstream infile("NECK_AP
UL, 217.061, -40.782n
UR, 295.625, -40.782n
LL, 217.061, 39.194n
LR, 295.625, 39.194");
infile.imbue(std::locale(std::locale(), new reader));
std::vector<std::string> d { std::istream_iterator<std::string>(infile),
std::istream_iterator<std::string>() };
std::copy(d.begin(), d.end(), std::ostream_iterator<std::string>(std::cout, "n"));
return 0;
}
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 如何使用默认参数等选择模板专业化
- 具有默认模板参数的多态类的模板推导失败
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 初始化具有非默认构造函数的std::数组项的更好方法
- 何时提供默认参数作为模板参数
- 是默认情况下分配给char数组常量的值
- 具有默认值的引用获取函数
- 具有默认模板类型的默认构造函数的类型推导
- EASTL矢量<向量<int>>连续的
- 当给定默认值时,为什么此模板参数推导失败
- 修改 VS Code 中的默认C++代码段
- 声明默认的模板化函数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何使用非默认构造函数实例化模板化类
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 格式化浮点值:返回默认值