Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Wednesday, March 2, 2011

Examples of istringstream

Some examples of istringstream, which is fun:

Sample 1: 
m_string::cacluation_string(const string & s) {
if (s.empty() || s.length() < 3) {
return "";
}
if ((s[0] != '-') && (s[0] < '0') && (s[0] > '9')) {
return "";
}
string oper1, oper2;
for(int i = 1; i < s.length(); i++) {
if (s[i] == '+' || s[i] == '-') {
oper1 = s.substr(0, i);
oper2 = s.substr(i);
break;
}
}
int iOper1, iOper2;
std::istringstream iss(oper1);
iss >> iOper1;
std::istringstream iss2(oper2);
iss2 >> iOper2;
string sret = "";
std::stringstream out;
out << iOper1 + iOper2;
sret = out.str();
cout<<" --- "<<sret<<endl;
return sret;
}


======Sample 2===========
ifstream file;
file.open("file.txt");
string line;

getline(file,line);
istringstream iss(line);
iss >> id;

getline(file,line);
istringstream iss2(line);
iss2 >> id;

getline(file,line);
iss.clear()
iss.str(line);
iss >> id;

======Sample 3===========
The "str()" and "str( string )" methods should work.
However, on some platforms these may not work so you
may use the ugly reconstruct hack.


#include <sstream>
#include <iostream>

int main()
{

std::istringstream iss( "Hi there" );
std:stringstream oss;

std::string foo;

iss >> foo;
oss << foo;

iss.str( "boo hoo" ); // Set the input to new string

iss >> foo;
oss << foo;
std::cout << oss.str() << "\n";

// Another way is to reconstruct the istringstream
// UGLY but some implementations have bugs and this is the
// only way.
iss.~istringstream();
new ( (void *) &iss ) std::istringstream( "Reconstruct this" );

oss.str( "" ); // reset the output string.

iss >> foo;
oss << foo;
std::cout << oss.str() << "\n";

// Another way is to reconstruct the ostringstream
oss.~ostringstream();
new ( (void *) &oss ) std:stringstream;

iss >> foo;
oss << foo;
std::cout << oss.str() << "\n";

}

Refs: http://www.velocityreviews.com/forums/t278533-std-stringstream-reset.html

--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

No comments:

Post a Comment