Sunday, September 8, 2013

Converting between strings and numbers

Something that should be easy seems to be more difficult than expected. Below as some conversion code not fully understood at the time of writing - i.e. have to understand the difference between ostringstream and stringstream.
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{

    int x = 1234;
    int y;
    string result;

    // converts integer to string which is held in result
    ostringstream conv;
    conv << x * 2;
    conv << 000; //gives a funny result - adds on a 0 at the end of the stream because we are only adding on zero as an integer, but after conversion....
    conv << "00"; //this does padd the result with two zeros - i.e similar to multiplying by 100
    cout << conv.str() << " converts number to string" << endl;
    result = conv.str();
    cout << result << " converted integer assigned to string variable" << endl;


    //takes the string created above and converts back to number
    stringstream string_to_num; // I tried this with conv
    string_to_num << result;

    string_to_num >> y;
    cout << y / 2000 << " output y and do numerical operations on y gets you back to x" << endl;

    return 0;
}

No comments:

Post a Comment