Question

Suppose you want to convert an integer into string this is the method in c++

    int c1=999;
    stringstream ss;
    ss<<c1;
    string str=ss.str();

How is it converting into string in c++? What does the stringstream contains and in the 3rd line of the above program in that statement i.e I mean what does the left shift operator (as we know that the symbol '<<' is used for left shifting) is doing here to converting into string

Was it helpful?

Solution

To convert an int to string (very basically), you have to go through all digits, translate it to a regular char, and put it in the string :

int toConvert = 999;
string res = "";

while (toConvert)
{
  int lastDigit = toConvert % 10; //retrieve last digit
  char c = lastDigit + '0';       //translate it to the char corresponding
  string reverse(c);      //We have to add it in front of the string, or otherwise 
  reverse.append (res);   // the digits will be reversed.
  res = reverse;
  toConvert /= 10;
}

This is a very basic way to translate int to string, and I'm sure it's done way better in the operator "<<", but you get the idea.

OTHER TIPS

The left shift here is overload by append function, think of it as ss.append(c1) where the append can have multiple functions append(int i) append(string s) append(byte b) etc

each function do the actual translation to the right string and appending it...

There's no left shift operator in your code. In C, << was left shift. In C++, it's the stream insertion operator (with support for left shift as well, for reasons of C compatibility).

You are allowed to overload various operators in C++, including bitwise left shift <<. Conceptually you can override it do to anything; the only restriction being that the number of operands can't be changed.

The streaming classes in the C++ IO stream libraries exploit this. It's syntatically cute to use << to write the argument to the stream in some way, as clearly, bitwise shifting a stream has no meaning so the operator may as well be used to do something else. That is what ss<<c1; is doing. It's not doing anything like a bitwise shift.

There is a school of thought that says that operator overloading is confusing (perhaps this is why this question has been asked). That's why operator overloading didn't make it into Java.

<< in this situation isn't exactly the Left Shift Operator.

Its a Stream Operator.

It appends (inserts) the characters in to your string stream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top