Converting int to std::string using istringstream inserts commas
Hi,
So I have a following function that converts int to string however it inserts the commas for thousands, millions, and so on. e.g. 65432 -> "65,432".
How do I make the conversion but have a string without commas?
I know it has to with locale but I cannot find it how to prevent it. Also I know about std::stoi() and atoi() but I do not want them.
Here is the code and thank you.
Code:
template <typename T>
std::string NumberToString ( T Number )
{
std::stringstream ss;
ss << Number;
return ss.str();
}
Re: Converting int to std::string using istringstream inserts commas
Quote:
Originally Posted by vincegata
Also I know about std::stoi() and atoi() but I do not want them.
Why not?
Re: Converting int to std::string using istringstream inserts commas
Quote:
Originally Posted by
vincegata
Here is the code and thank you.
Code:
template <typename T>
std::string NumberToString ( T Number )
{
std::stringstream ss;
ss << Number;
return ss.str();
}
Exactly what code is this? There is no way this function as it stands inserts commas into the numbers.
To place commas, you have to do a little more work than just streaming a number to a stringstream object (a call to imbue and the locale to use needs to be done).
Regards,
Paul McKenzie
Regards,
Paul McKenzie
Re: Converting int to std::string using istringstream inserts commas
This program using your template function
Code:
#include <iostream>
#include <sstream>
using namespace std;
template <typename T>
std::string NumberToString ( T Number )
{
std::stringstream ss;
ss << Number;
return ss.str();
}
int main()
{
int n = 1234567;
double d = 34567.8;
cout << NumberToString<int>(n) << endl;
cout << NumberToString<double>(d) << endl;
return 0;
}
produces the output
without any commas. So I'm confused as to how you think the function does insert commas? :confused:
Re: Converting int to std::string using istringstream inserts commas
Quote:
Originally Posted by Paul McKenzie
There is no way this function as it stands inserts commas into the numbers.
Quote:
Originally Posted by 2kaud
So I'm confused as to how you think the function does insert commas?
I have never seen it done myself, but there is locale support for numeric formatting with thousands place separators in the C++ standard library, so it may be the case that vincegata's default locale has this enabled and it is somehow actually in effect for stringstreams.