How do I convert String to Int using String Stream *solved*

Started by
11 comments, last by utilae 17 years, 9 months ago
How do I convert String to Int using String Stream ? I am using C++. Here's what I got so far:

//g_StrStream is a string stream object
int nNumber;
string sString="5";
g_StrStream<<sString;	
nNumber=g_StrStream;//convert string to int
g_StrStream.str("");//erase string stream




Anyone able to help? [Edited by - utilae on July 29, 2006 8:28:55 PM]

HTML5, iOS and Android Game Development using Corona SDK and moai SDK

Advertisement
First, I highly recommend not using a global stringstream object. Also consider using boost::lexical_cast for this kind of thing. However, to answer the question:
g_StrStream.str(sString);g_StrStream >> nNumer;

If you use a global stringstream object keep in mind that you may need to clear the eof bit after an extraction.
To get the string of the stream you need to call str(), so your code should look like this:
//g_StrStream is a string stream objectint nNumber;string sString="5";g_StrStream<<sString;	nNumber=g_StrStream.str();//convert string to intg_StrStream.str("");//erase string stream


Quote:Original post by CTar
nNumber=g_StrStream.str();//convert string to int

Say what? There's no conversion from std::string to int.
Quote:Original post by CTar
To get the string of the stream you need to call str(), so your code should look like this:
//g_StrStream is a string stream objectint nNumber;string sString="5";g_StrStream<<sString;	nNumber=g_StrStream.str();//convert string to intg_StrStream.str("");//erase string stream
'nNumber' is an int in the OP's example, not a string. (Also, another vote for boost::lexical_cast<>()).
Hmm, I try this:
int nNumber;string sString="5";g_StrStream.str(sString);g_StrStream>>nNumber;//convert string to int


And get a ton of errors (84 of these):
error C2784: could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &' from 'std::ostringstream'

HTML5, iOS and Android Game Development using Corona SDK and moai SDK

Are you sure you #included <sstream>?
Yes:

//string, string stream
#include "string"
using std::string;
#include "sstream"
using namespace std;

HTML5, iOS and Android Game Development using Corona SDK and moai SDK

When you defined g_StrStream, did you define as a stringstream, ostringstream or an istringstream?
ostringstream g_StrStream;//string stream

What are the differences between the three and which do I need?

HTML5, iOS and Android Game Development using Corona SDK and moai SDK

This topic is closed to new replies.

Advertisement