Ярлыки

понедельник, 14 декабря 2009 г.

c++. Convert string to int.

c-style:

#include
#include
#include

int GetIntVal(string strConvert) {
int intReturn;

// NOTE: You should probably do some checks to ensure that
// this string contains only numbers. If the string is not
// a valid integer, zero will be returned.
intReturn = atoi(strConvert.c_str());

return(intReturn);
}

c++ style:

using namespace std;
string s = "123";
int i;
bool success;
istringstream myStream(s);

if (myStream>>i)
success = true;
else
success = false;

#include 
#include

int main(void) {
using namespace std;

istringstream from;
ostringstream to;
int i;

to << 15;

cout << to.str() << endl;

from = to.str();
from >> i;

cout << i << endl;

return 0;
}