【问题标题】:Avoid operator>> to break input at whitespaces避免 operator>> 在空格处中断输入
【发布时间】:2013-07-14 17:14:17
【问题描述】:

我正在重载operator>> 函数。它应该在输入中输入一个字符串,需要一些空格,在空格处分解字符串并执行与主题无关的其他操作。

我有这个代码:

std::istream& operator>>(std::istream &in, Foo &f) {
    std::string str;
    in >> str;
    std::cout << "str = " << str << std::endl; // for testing
    // ...
    return in;
}

假设把这个字符串(一个复数)作为输入:

3 + 2i

std::cout 函数仅打印 3。我试过把flagstd::noskipws放上去,但问题依旧存在。

有没有办法解决这个问题?

【问题讨论】:

    标签: c++ string operator-overloading


    【解决方案1】:

    使用std::getline函数读取完整的输入行:

    std::getline(in, str);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-17
      • 2023-03-10
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多