//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
How do I convert String to Int using String Stream *solved*
How do I convert String to Int using String Stream ?
I am using C++.
Here's what I got so far:
Anyone able to help?
[Edited by - utilae on July 29, 2006 8:28:55 PM]
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:
If you use a global stringstream object keep in mind that you may need to clear the eof bit after an extraction.
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'nNumber' is an int in the OP's example, not a string. (Also, another vote for boost::lexical_cast<>()).
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
Hmm, I try this:
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'
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'
Yes:
//string, string stream
#include "string"
using std::string;
#include "sstream"
using namespace std;
//string, string stream
#include "string"
using std::string;
#include "sstream"
using namespace std;
When you defined g_StrStream, did you define as a stringstream, ostringstream or an istringstream?
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement