写入文件时,将双圆点转换为逗号
Converting dots in double to comma when writing to file
我正在研究一个小的导出函数,我需要编写由6x doubles
组成的100万行。不幸的是,读取数据的工具要求将点替换为逗号。我现在转换它们的方式是通过在编辑器中手动替换,这对于一个大约20MB的文件来说是非常麻烦和极其缓慢的。
是否有一种方法可以在写作时进行这种转换?
使用tr
这样的工具会比手动做更好,应该是你的首选。否则,它就相当简单了输入通过滤波流,转换所有的'.'
转换为','
,甚至仅在特定上下文中转换(当例如,前面或后面的字符是数字)。没有上下文:
class DotsToCommaStreambuf : public std::streambuf
{
std::streambuf* mySource;
std::istream* myOwner;
char myBuffer;
protected:
int underflow()
{
int ch = mySource->sbumpc();
if ( ch != traits_type::eof() ) {
myBuffer = ch == '.' ? ',' : ch;
setg( &myBuffer, &myBuffer, &myBuffer + 1 );
}
}
public:
DotsToCommaStreambuf( std::streambuf* source )
: mySource( source )
, myOwner( NULL )
{
}
DotsToCommaStreambuf( std::istream& stream )
: mySource( stream.rdbuf() )
, myOwner( &stream )
{
myOwner->rdbuf( this );
}
~DotsToCommaStreambuf()
{
if ( myOwner != NULL ) {
myOwner.rdbuf( mySource );
}
}
}
用这个类包装输入源:
DotsToCommaStreambuf s( myInput );
只要s
在作用域中,myInput
将转换所有'.'
它在','
的输入中看到的。
编辑:
我已经看到了您希望发生更改的注释在生成文件时,而不是在读取文件时。的原理是相同的,除了过滤流具有为ostream
所有者,并覆盖overflow( int )
,而不是underflow
。在输出时,不需要本地缓冲区,所以甚至更简单:
int overflow( int ch )
{
return myDest->sputc( ch == '.' ? ',' : ch );
}
我会使用c++算法库并使用std::replace
来完成工作。将整个文件读入string
并调用replace:
std::string s = SOME_STR; //SOME_STR represents the set of data
std::replace( s.begin(), s.end(), '.', ','); // replace all '.' to ','
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将生成文件转换为 CMakeLists.txt等效项
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 将文件复制到自定义位置,存在字符串转换问题
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 将模板类转换为标头和 cpp 文件
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- 如何使用 C++将 2D RGB 数组转换为 dds 文件?
- 如何将二进制文件头示例代码 (C++/C#) 转换为 Python?
- 在 c++ 中逐行读取文件(将代码从 Python 转换为 C++)
- 将调用类转换为库本身后,库头文件上没有这样的文件
- 如何使用C++将.trc文件类型转换为文本文件?
- 将 boost::文件系统::p ath 转换为 char?
- 如何将 .ui 完全转换为 C++ 头文件和源文件
- 转换 mp4 文件并将其流式传输到带有树莓派的查看器
- Makefiles:转换文件扩展名
- .cpp错误:与"std::cerr "中的"运算符<"不匹配<"正在转换文件 \" ""
- 从c++基础转换文件