KristinaDimi
KristinaDimi

Reputation: 13

C++ String Stream

I'm just learning how to use streams in C++ and I have one question.

I thought that each stream has state true or false. I want to enter each word from the string below and 1 until there is a word, but I get an error:

cannot convert 'std::istringstream {aka std::__cxx11::basic_istringstream<char>}' to 'bool' in initialization
bool canReadMore = textIn;

It should be like:

antilope  
1  
ant  
1  
antagonist  
1  
antidepressant  
1

What am I doing wrong?

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

Upvotes: 1

Views: 453

Answers (1)

Escualo
Escualo

Reputation: 42072

Since C++11, std::istringstream operator bool is explicit. What this means is that you must explicitly make the cast yourself:

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

Output:

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

0

Now, if you use a std::stringstream in a bool context, the conversion will be automatic. This is an idiomatic use:

#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";
  }
}

Output:

antilope
ant
antagonist
antidepressant

Upvotes: 4

Related Questions