写入文件时,将双圆点转换为逗号

Converting dots in double to comma when writing to file

本文关键字:转换 文件      更新时间:2023-10-16

我正在研究一个小的导出函数,我需要编写由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 ','