sbakic's blog

By sbakic, history, 9 years ago, In English

According to this, we can use to_string() only with compiler higher than GCC 4.8.0 and with C++ 11.

But I submitted with GNU C++ 11 4.9.2 (12720137) and got this error.

I know there are other solutions to convert int to string, but I want to know what is problem with this one. I am using compiler GNU C++ 11 5.1.0 and it's working on my computer. Thanks.

UPD: Tutorial

This will be a quick tutorial about stringstream, istringstream and ostringstream. It may be usefull for someone.

istream and ostream: Interfaces to streaming data (files, sockets, etc.).

istringstream: An istream that wraps a string and offers its contents.

ostringstream: An ostream that saves the content written to it as a string.

stringstream: An iostream can be used to both read strings and write data into strings.

The inheritance relationships between the classes

Difference between stringstream and ostringstream

Classes stringstream and ostringstream pass different flags to the stringbuf. The stringbuf of an ostringstream does not support reading. The way to extract characters from an ostringstream is by using the std :: ostringstream :: str() function. Using 'just' istringstream or ostringstream better expresses your intent and gives you some checking against silly mistakes such as accidental use of << vs >>. A stringstream is somewhat larger, and might have slightly lower performance; multiple inheritance can require an adjustment to the vtable pointer.

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Casting i and index to long long and sending it on Visual C++ helps, like: to_string((long long)i).

MinGW doesn't have such function.

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

to_string is missing in MinGW due to a bug. So it doesn't work on codeforces. You can still use THIS patch in your code to do the same.

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Here is a quick way to write a to_string method:

template<class T>
string to_string(T a) {
	string ans;
	stringstream ss;
	ss << a;
	ss >> ans;
	return ans;
}
  • »
    »
    9 years ago, # ^ |
    Rev. 2   Vote: I like it +6 Vote: I do not like it

    I used this code to get correct solution:

    #include <sstream>
    
    namespace patch {
      template <typename T> string to_string(const T& n) {
        ostringstream s;
        s << n;
        return s.str();
      }
    }
    

    In main() I used patch::to_string(int).

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    it is short, but so slow..

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it
      string to_string(int x){
          string ans;
          while(x){
              ans += char(x % 10 +'0');
              x /= 10;
          }
          return ans;
      }