Johnnie W
Johnnie W

Reputation: 127

Why does cleaning istringstream fail?

While converting a string to integer I just fail to clear my istringstream to place in another number. I have tried all kinds of different solutions but it just wont work. There are a few work arounds but I'd like to learn to know why...

So basically this is how my code looks like

#include <iostream>
#include <string>
#include <sstream>

int main() {

  std::string a = "153";
  std::string c = "2556";

  int b;

  std::istringstream convert(a);

  convert >> b;

  std::cout << b << std::endl;

  convert.str( std::string() );
  //convert.str("");
  convert.clear();

  convert(c);

  convert >> b;

  std::cout << b << std::endl;

  return 0;
}

And the following output error

C:\...\string to int.cpp|28|error: no match for call to '(std::istringstream {aka std::basic_istringstream<char>}) (std::string&)'|

Thanks :)

Upvotes: 0

Views: 271

Answers (2)

You can't call the constructor convert(c) of an object once already constructed. To set a new string to parse you need to call the function str(c). So you need to change it to:

convert.str(c);

Upvotes: 4

Pixelchemist
Pixelchemist

Reputation: 24946

convert(c); would require std::istringstream to define a function call operator operator() that can be called with an lvalue of type std::string. This is not the case.

You can use clear() and str():

std::string a = "153";
std::string c = "2556";
int b{ 0 };
std::istringstream convert{ a };
convert >> b;
std::cout << b << std::endl;
convert.clear();
convert.str(c);
convert >> b;
std::cout << b << std::endl;

Upvotes: 2

Related Questions