Click here to Skip to main content
15,895,799 members
Articles / Programming Languages / C++

Converting numeric types to strings and strings to numeric types

Rate me:
Please Sign up or sign in to vote.
4.77/5 (21 votes)
23 Feb 20047 min read 167.7K   1.4K   33  
Benchmarks on various conversion technqiues, commentary, and some custom conversion functions.
// conversion.cpp : Defines the entry point for the console application.
//

#include "convert.h"

#include <iostream>
#include <string>

using namespace std;

int main()
{
	cout.precision(50);
	string choice;
	char * buffer = new char[1000];
	bool repeat;
	do {
		cout << "String to convert: " << endl;
		cin.getline(buffer,1000);
		if(stricmp(buffer,"q") == 0 || stricmp(buffer,"quit") == 0)
			break;
		do {
			repeat = false;
			cout << "Convert to a double (d), an integer (i), unsigned integer (ui), or a 64bit integer (i64): " << endl;
			cin >> choice;
			cin.ignore(2,'\n');
			try
			{
				if(choice == "d")
					cout << "Result of the conversion: " << Convert::ToDouble(buffer,strlen(buffer)) << "\r\n" << endl;
				else if(choice == "i")
					cout << "Result of the conversion: " << Convert::ToInteger<int>(buffer,strlen(buffer)) << "\r\n" << endl;
				else if(choice == "ui")
					cout << "Result of the conversion: " << Convert::ToInteger<unsigned int>(buffer,strlen(buffer)) << "\r\n" << endl;
				else if(choice == "i64")
					cout << "Result of the conversion: " << Convert::ToInteger<__int64>(buffer,strlen(buffer)) << "\r\n" << endl;
				else
					repeat = true;
			}
			catch(InvalidConversionException)
			{
				cout << "Invalid Conversion!" << endl;
			}
			
		} while(repeat);
	} while(true);
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
I love to code. I've programmed in a dozen languages since I began in my final year of high school. My favourite languages are Python, C# and C++ in that order.

Comments and Discussions