【问题标题】:C++ String StreamC++ 字符串流
【发布时间】:2020-09-11 20:05:12
【问题描述】:

我刚刚学习如何在 C++ 中使用流,我有一个问题。

我认为每个流都有状态真或假。我想从下面的字符串中输入每个单词和 1 直到有一个单词,但是我得到一个错误:

无法在初始化中将 'std::istringstream {aka std::__cxx11::basic_istringstream}' 转换为 'bool'
bool canReadMore = textIn;

应该是这样的:

羚羊 1 蚂蚁 1 拮抗剂 1 抗抑郁药 1

我做错了什么?

int main() {
    
    std:: string text = "antilope ant antagonist antidepressant";
    std:: istringstream textIn(text);
    
    for(int i = 0; i < 5; i++ ){
        std:: string s;
        textIn >> s;
    
        bool canReadMore = textIn;
        std::cout << s << std:: endl;
        std::cout << canReadMore << std:: endl;
    
    }
    return 0;
    
}
``1

【问题讨论】:

    标签: c++ stream


    【解决方案1】:

    自 C++11 起,std::istringstream operator bool is explicit。这意味着您必须自己明确地进行演员表:

    #include <iostream>
    #include <sstream>
    #include <string>
    
    int main() {
      std::string        text = "antilope ant antagonist antidepressant";
      std::istringstream textIn(text);
    
      for (int i = 0; i < 5; i++) {
        std::string s;
        textIn >> s;
    
        bool canReadMore = bool(textIn);
        std::cout << s << std::endl;
        std::cout << canReadMore << std::endl;
      }
      return 0;
    }
    

    输出:

    ./a.out 
    antilope
    1
    ant
    1
    antagonist
    1
    antidepressant
    1
    
    0
    

    现在,如果您在 bool 上下文中使用 std::stringstream,则转换将是自动的。这是一个惯用的用法:

    #include <iostream>
    #include <sstream>
    #include <string>
    
    int main() {
      std::string        text = "antilope ant antagonist antidepressant";
      std::istringstream textIn(text);
    
      std::string s;
      while (textIn >> s) {
        std::cout << s << "\n";
      }
    }
    

    输出:

    antilope
    ant
    antagonist
    antidepressant
    

    【讨论】:

    • 更重要的是,请注意在原始版本中,在循环退出之前如何打印空字符串。这是因为在读取字符串 (&gt;&gt;) 之后 设置了 fail 标志。所以应该在 after &gt;&gt; 之后检查,而不是之前。
    • 非常感谢
    • 请注意,bool canReadMore = bool(textIn) 是一种函数式强制转换,虽然这会起作用,但应尽可能避免使用旧的 C 式强制转换(即bool canReadMore = (bool)textIn;)和函数式强制转换。首选方法是使用显式 C++ 风格的static_cast,例如:bool canReadMore = static_cast&lt;bool&gt;(textIn);
    猜你喜欢
    • 2011-12-29
    • 2014-08-08
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2014-05-05
    • 1970-01-01
    相关资源
    最近更新 更多