How can I convert a char that has this info in it "312,000" to a double?
I know I can use atof but it doesnt work with the comma.. is there any way to remove the comma.. or to use atof when theres non numeric values in the char?

Thanks

Recommended Answers

All 4 Replies

Pre-process your string to remove the comma, then use strtod()

A char cannot hold "312,000". You are probably thinking about
an array of chars, or a string. Use something like this :

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string deleteChar(string str, char charDelete = ','){
	size_t pos = str.find(charDelete);
	if(pos == string::npos) return str;
	str.erase( pos, 1);
	return str;
}
size_t convertFromString(string strNum){
	stringstream converter;
	size_t value = 0;
	converter << strNum; //insert string into our stream
	converter >> value; //extract data into our variable
	//check if conversion was good
	if(converter.fail() ) throw std::exception(" Error converting " );
	return value;
}
size_t myConvert(string strNum){

	while(strNum.find(',') != string::npos) //while comma is there
		strNum = deleteChar(strNum); //delete the comma

	size_t value = convertFromString(strNum); //convert string to size_t

	return value;
}
int main ()
{	
	size_t value = myConvert("1,000,000");
	cout << value * 2 << endl;

	return 0;
}

Or loop through the 'char' and use the num = (num * 10) + char process.

>Or loop through the 'char' and use the num = (num * 10) + char process.
Nine times out of ten, this algorithm breaks on edge cases. Unless it's a homework problem, such a manual process isn't recommended when there are better alternatives like std::stringstream.

>Use something like this
Manually removing the commas smells kludgy. You can easily imbue the stringstream with a suitable locale and all of that work will be done by the library:

#include <iostream>
#include <locale>
#include <sstream>
#include <string>
#include <typeinfo>

template <typename T>
T parse ( const std::string& s, std::locale loc = std::locale ( "C" ) )
{
  std::istringstream in ( s );
  T result;

  in.imbue ( loc );

  if ( !( in>> result ) || !in.eof() ) {
    std::ostringstream err;

    err<<"Could not convert to type "<< typeid ( T ).name()
       <<" at "<< in.rdbuf();

    throw std::invalid_argument ( err.str() );
  }

  return result;
}

int main()
{
  try {
    const char *p = "312,000";

    // This is the important part. The "C" locale expects
    // no digit separators, but the "" locale uses local
    // area conventions (commas in my case)
    double d = parse<double> ( p, std::locale ( "" ) );

    std::cout<<"The value is "<< d <<'\n';
  } catch ( std::invalid_argument& ex ) {
    std::cout<<"Invalid floating-point value: "<< ex.what() <<'\n';
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.