C++ Data Type Casting

Description

C++ Data Type Casting

#include <iostream>
#include <sstream> 

using namespace std;

int StringToNumber(string MyString)
{
    istringstream converter(MyString); // Converts from string to number.
    int result;                        // Contains the operation results.

    // Perform the conversion and return the results.
    converter >> result;//from  w  ww  . ja  va2 s.c o  m
    return result;
}

string NumberToString(int Number)
{
    ostringstream converter; // Converts from number to string.

    // Perform the conversion and return the results.
    converter << Number;
    return converter.str();
}

int main()
{
    float myFloat; // Contains the theoretical number of kids.
    int myInt;     // Contains an actual number of kids.

    cout << "Float to Integer" << endl;
    cout << "(Truncated)" << endl;
    myFloat = 2.5;
    myInt = (int)myFloat;
    cout << myFloat << " " << myInt << endl;

    myFloat = 2.1;
    myInt = (int)myFloat;
    cout << myFloat << " " << myInt << endl;

    myFloat = 2.9;
    myInt = (int)myFloat;
    cout << myFloat << " " << myInt << endl;
    cout << "Float to Integer" << endl;

    cout << "(Rounded)" << endl;
    myFloat = 2.5;
    myInt = (int)(myFloat + .5);
    cout << myFloat << " " << myInt << endl;

    // use the StringToNumber() function to perform the conversion.
    myInt = 3;
    myFloat = myInt;
    cout << myFloat << endl << endl;
    cout << "String to number" << endl;
    int x = StringToNumber("12345") * 50;
    cout << x << endl << endl;

    // use the NumberToString() function to perform the conversion.
    cout << "Number to string" << endl;
    string mystring = NumberToString(80525323);
    cout << mystring << endl;

    return 0;
}



PreviousNext

Related