我们可以更改字符串流对象的重载运算符">>"默认行为吗?

Can we change the default behavior of ">>" overloaded operator for stringstream object?

本文关键字:gt 默认 运算符 重载 字符串 对象 我们      更新时间:2023-10-16

我的需求描述如下。我正在读取包含

的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;
}