(stringstream)mystr vs. stringstream(mystr)

Hi,

I'm new to coding and just finished the Compound data types -> Data structures tutorial. In the pointers to structures example I stumbled across a line (24) which slightly confused me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// pointers to structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
};

int main ()
{
  string mystr;

  movies_t amovie;
  movies_t * pmovie;
  pmovie = &amovie;

  cout << "Enter title: ";
  getline (cin, pmovie->title);
  cout << "Enter year: ";
  getline (cin, mystr);
  (stringstream) mystr >> pmovie->year;

  cout << "\nYou have entered:\n";
  cout << pmovie->title;
  cout << " (" << pmovie->year << ")\n";

  return 0;
}


In previous examples the stringstream command always looked like

 
stringstream (mystr) >> pmovie->year;

I replaced the original line from the example code with the one above and it did work as well.
Could someone tell me if there is a difference between both versions, please?

Actually, I don't understand why

 
(stringstream) mystr >> pmovie->year;

even works.

Thanks in advance.
Last edited on
Given a value to type A and a different type B, (B)value and B(value) are equivalent if B defines a non-explicit constructor that accepts a parameter of type A.
(B)value is the type casting syntax inherited from C.
1
2
3
4
double pi = 3.141592;
std::cout << (int)pi << std::endl;
const char *s = "Hello, World!\n";
std::cout << (uintptr_t)s << std::endl;


EDIT: It just occurred to me that perhaps what confused you was the precedence.
(stringstream) mystr >> pmovie->year; does not mean (stringstream) (mystr >> pmovie->year);. It means ((stringstream) mystr) >> pmovie->year;.
Last edited on
Hi helios,

tanks for your reply.

I wasn't aware of type casting at this point. Since I didn't made it to the Type casting tutorial yet, I expected stringstream to behave like a function.

Your answer helped me a lot :)
Last edited on
std::stringstream is a class that inherits std::iostream and uses an internal bufffer instead of an I/O device. It's useful to convert between strings an numbers, for example.
1
2
3
4
5
6
7
8
std::stringstream stream("12");
int i;
stream >> i;
assert(i == 12);
std::stringstream stream2;
stream2 << i * 2;
std::string s = stream2.str();
assert(s == "24");
Topic archived. No new replies allowed.