C++ format int numbers to separate thousands with a dot - c++

I'm working on Eclipse, on Fedora. I want to make a number more understandable using a dot to separate the thousands. This number is an integer Value that can be 0<Value<99.999
So... if Value = 1000 it shows 1000 and what I want is to show 1.000 (note the dot). The code I need to change is the next one:
char str[12];
sprintf(str, "%d", (int)(Value));
m_Text.SetText(str);
And what I thought is to do something like:
if (Value > 999)
{
int RightPart = (int)Value % 1000;
int LeftPart = Val/1000 ;
}
And then append in a string LeftPart + "." + RightPart so if Value = 1563 it will be 1+.+563 which is 1.563
My problem is that it's very ugly to do this and I was wondering if there were a better way of doing it. I've searched on google and found imbueand localebut they are only for cout. I've see too some posts like this and this but this doesn't help me with my problem.
Thank you.
NOTE: I want to remark that I DON'T WANT to change the output format. I want to change the int I receive so I can have the dots in the str var with which I will work later.
NOTE 2: Basically the code has to: receive an integer (Value), and send it like a string to setText(). setText() will basically print it on the screen where and when it has to, and I want it to print 1.563 and not 1563 which is more difficult to read.

Use stringstream and same imbue technique for it.
For example:
struct dotted : std::numpunct<char> {
char do_thousands_sep() const { return '.'; } // separate with dots
std::string do_grouping() const { return "\3"; } // groups of 3 digits
static void imbue(std::ostream &os) {
os.imbue(std::locale(os.getloc(), new dotted));
}
};
and then:
std::stringstream ss;
dotted::imbue(ss);
ss << Value;
std::cout << ss.str();
Demo

#include <iomanip>
#include <locale>
#include <iostream>
#include <sstream>
using namespace std;
template<class T>
string format(T value)
{
stringstream ss;
ss.imbue(locale(""));
ss << fixed << value;
return ss.str();
}
int main(int argc, char argv[])
{
cout.imbue(locale(""));
cout << 1000000 << endl;
return 0;
}
Prints:
1.000.000
You should probably look at which locale is used when "" is passed and change it with a more appropriate one.
Or vice versa:
int str_to_nr(string str)
{
int val;
stringstream ss(str);
ss.imbue(locale(""));
ss >> val;
return val;
}
int main(int argc, char argv[])
{
cout << str_to_nr("1.000") << endl;
return 0;
}
Prints:
1000

#gandgandi's answer basically gives you a technique to print out the value with dots on demand using C++ streams.
sprintf (which is generally not safe to use, BTW) is a C library function. C does not provide a mechanism to alter the locale behavior in the same way C++ provides. In C, you will have to define the locale behavior with mechanisms/tools provided by your operating system and assign it a name. Then, you can use the C function setlocale to alter the locale in the program to the one you have created to get it to print how you want. However, this will only work on machines that have the locale you have created installed. It won't work on any other machine.
With only a little bit of work and almost no creative effort, you can just use the C++ solution already provided combined with a call to sprintf.
char str[12];
stringstream ss;
dotted::imbue(ss);
ss << Value;
sprintf(str, "%s", ss.str());
m_Text.SetText(str);
But, there is really no reason to use sprintf at all:
stringstream ss;
dotted::imbue(ss);
ss << Value;
m_Text.SetText(ss.str());

Related

How can I enter (i+1) as a string? [duplicate]

What is the easiest way to convert from int to equivalent string in C++? I am aware of two methods. Is there an easier way?
(1)
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(2)
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.
#include <string>
std::string s = std::to_string(42);
is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:
auto s = std::to_string(42);
Note: see [string.conversions] (21.5 in n3242)
C++20: std::format would be the idiomatic way now.
C++17:
Picking up a discussion with #v.oddou a couple of years later, C++17 has delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro ugliness.
// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
std::ostringstream sstr;
// fold expression
( sstr << std::dec << ... << args );
return sstr.str();
}
Usage:
int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
C++98:
Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
Usage is as easy as could be:
int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );
The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.
Current C++
Starting with C++11, there's a std::to_string function overloaded for integer types, so you can use code like:
int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);
The standard defines these as being equivalent to doing the conversion with sprintf (using the conversion specifier that matches the supplied type of object, such as %d for int), into a buffer of sufficient size, then creating an std::string of the contents of that buffer.
Old C++
For older (pre-C++11) compilers, probably the most common easy way wraps essentially your second choice into a template that's usually named lexical_cast, such as the one in Boost, so your code looks like this:
int a = 10;
string s = lexical_cast<string>(a);
One nicety of this is that it supports other casts as well (e.g., in the opposite direction works just as well).
Also note that although Boost lexical_cast started out as just writing to a stringstream, then extracting back out of the stream, it now has a couple of additions. First of all, specializations for quite a few types have been added, so for many common types, it's substantially faster than using a stringstream. Second, it now checks the result, so (for example) if you convert from a string to an int, it can throw an exception if the string contains something that couldn't be converted to an int (e.g., 1234 would succeed, but 123abc would throw).
I usually use the following method:
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
It is described in details here.
You can use std::to_string available in C++11 as suggested by Matthieu M.:
std::string s = std::to_string(42);
Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::format_int from the {fmt} library to convert an integer to std::string:
std::string s = fmt::format_int(42).str();
Or a C string:
fmt::format_int f(42);
const char* s = f.c_str();
The latter doesn't do any dynamic memory allocations and is more than 70% faster than libstdc++ implementation of std::to_string on Boost Karma benchmarks. See Converting a hundred million integers to strings per second for more details.
Disclaimer: I'm the author of the {fmt} library.
If you have Boost installed (which you should):
#include <boost/lexical_cast.hpp>
int num = 4;
std::string str = boost::lexical_cast<std::string>(num);
It would be easier using stringstreams:
#include <sstream>
int x = 42; // The integer
string str; // The string
ostringstream temp; // 'temp' as in temporary
temp << x;
str = temp.str(); // str is 'temp' as string
Or make a function:
#include <sstream>
string IntToString(int a)
{
ostringstream temp;
temp << a;
return temp.str();
}
Not that I know of, in pure C++. But a little modification of what you mentioned
string s = string(itoa(a));
should work, and it's pretty short.
sprintf() is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.
Using stringstream for number conversion is dangerous!
See std::ostream::operator<< where it tells that operator<< inserts formatted output.
Depending on your current locale an integer greater than three digits, could convert to a string of four digits, adding an extra thousands separator.
E.g., int = 1000 could be converted to a string 1.001. This could make comparison operations not work at all.
So I would strongly recommend using the std::to_string way. It is easier and does what you expect.
From std::to_string:
C++17 provides std::to_chars as a higher-performance locale-independent alternative.
First include:
#include <string>
#include <sstream>
Second add the method:
template <typename T>
string NumberToString(T pNumber)
{
ostringstream oOStrStream;
oOStrStream << pNumber;
return oOStrStream.str();
}
Use the method like this:
NumberToString(69);
or
int x = 69;
string vStr = NumberToString(x) + " Hello word!."
In C++11 we can use the "to_string()" function to convert an int into a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x = 1612;
string s = to_string(x);
cout << s<< endl;
return 0;
}
C++17 provides std::to_chars as a higher-performance locale-independent alternative.
If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is the example for little-endian architectures (all x86, x86_64 and others):
If you are converting a two-digit number:
int32_t s = 0x3030 | (n/10) | (n%10) << 8;
If you are converting a three-digit number:
int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;
If you are converting a four-digit number:
int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;
And so on up to seven-digit numbers. In this example n is a given integer. After conversion it's string representation can be accessed as (char*)&s:
std::cout << (char*)&s << std::endl;
Note: If you need it on big-endian byte order, though I did not tested it, but here is an example: for three-digit number it is int32_t s = 0x00303030 | (n/100)<< 24 | (n/10%10)<<16 | (n%10)<<8; for four-digit numbers (64 bit arch): int64_t s = 0x0000000030303030 | (n/1000)<<56 | (n/100%10)<<48 | (n/10%10)<<40 | (n%10)<<32; I think it should work.
It's rather easy to add some syntactical sugar that allows one to compose strings on the fly in a stream-like way
#include <string>
#include <sstream>
struct strmake {
std::stringstream s;
template <typename T> strmake& operator << (const T& x) {
s << x; return *this;
}
operator std::string() {return s.str();}
};
Now you may append whatever you want (provided that an operator << (std::ostream& ..) is defined for it) to strmake() and use it in place of an std::string.
Example:
#include <iostream>
int main() {
std::string x =
strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
std::cout << x << std::endl;
}
Use:
#define convertToString(x) #x
int main()
{
convertToString(42); // Returns const char* equivalent of 42
}
int i = 255;
std::string s = std::to_string(i);
In C++, to_string() will create a string object of the integer value by representing the value as a sequence of characters.
I use:
int myint = 0;
long double myLD = 0.0;
string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();
It works on my Windows and Linux g++ compilers.
Here's another easy way to do
char str[100];
sprintf(str, "%d", 101);
string s = str;
sprintf is a well-known one to insert any data into a string of the required format.
You can convert a char * array to a string as shown in the third line.
If you're using MFC, you can use CString:
int a = 10;
CString strA;
strA.Format("%d", a);
C++11 introduced std::to_string() for numeric types:
int n = 123; // Input, signed/unsigned short/int/long/long long/float/double
std::string str = std::to_string(n); // Output, std::string
Use:
#include<iostream>
#include<string>
std::string intToString(int num);
int main()
{
int integer = 4782151;
std::string integerAsStr = intToString(integer);
std::cout << "integer = " << integer << std::endl;
std::cout << "integerAsStr = " << integerAsStr << std::endl;
return 0;
}
std::string intToString(int num)
{
std::string numAsStr;
bool isNegative = num < 0;
if(isNegative) num*=-1;
do
{
char toInsert = (num % 10) + 48;
numAsStr.insert(0, 1, toInsert);
num /= 10;
}while (num);
return isNegative? numAsStr.insert(0, 1, '-') : numAsStr;
}
All you have to do is use String when defining your variable (String intStr). Whenever you need that variable, call whateverFunction(intStr.toInt())
Using the plain standard stdio header, you can cast the integer over sprintf into a buffer, like so:
#include <stdio.h>
int main()
{
int x = 23;
char y[2]; // The output buffer
sprintf(y, "%d", x);
printf("%s", y)
}
Remember to take care of your buffer size according to your needs (the string output size).
string number_to_string(int x) {
if (!x)
return "0";
string s, s2;
while(x) {
s.push_back(x%10 + '0');
x /= 10;
}
reverse(s.begin(), s.end());
return s;
}
This worked for me -
My code:
#include <iostream>
using namespace std;
int main()
{
int n = 32;
string s = to_string(n);
cout << "string: " + s << endl;
return 0;
}
I think using stringstream is pretty easy:
string toString(int n)
{
stringstream ss(n);
ss << n;
return ss.str();
}
int main()
{
int n;
cin >> n;
cout << toString(n) << endl;
return 0;
}
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
namespace std
{
inline string to_string(int _Val)
{ // Convert long long to string
char _Buf[2 * _MAX_INT_DIG];
snprintf(_Buf, "%d", _Val);
return (string(_Buf));
}
}
You can now use to_string(5).
You use a counter type of algorithm to convert to a string. I got this technique from programming Commodore 64 computers. It is also good for game programming.
You take the integer and take each digit that is weighted by powers of 10. So assume the integer is 950.
If the integer equals or is greater than 100,000 then subtract 100,000 and increase the counter in the string at ["000000"];
keep doing it until no more numbers in position 100,000.
Drop another power of ten.
If the integer equals or is greater than 10,000 then subtract 10,000 and increase the counter in the string at ["000000"] + 1 position;
keep doing it until no more numbers in position 10,000.
Drop another power of ten
Repeat the pattern
I know 950 is too small to use as an example, but I hope you get the idea.

Control the Precision of float number in a string - C++

I'm trying to control the number of Digits i add in a String , but I couldn't control it since i am printing an Array of Strings .
float loads[n] = { 1,2,3,0.05,1,2,3,0.5,1,2,3,3,1,2 };
string print[nBits] = { "" };
int n=14;
int BB;
.
.
.
void main(){
for (int j = 0; j < nBits; ++j)// 2^n
{
for (int i = 0; i < n; ++i) // n
{
BB = arr[j][i];
R = loads[i];
if (BB == 1) {
print[j]+="" +std::to_string(loads[i])+"//";
}
}
}
But i eventually get an Array of strings that Looks like this :
0.050000//3.000000//...
Is there any way to control the Precision of the floating number before adding it to the String ?
(so i can have a resulting string control a fixed number of Digits instead)
0.05//3.00// ...
Use std::stringstream together with std::fixed and std::setprecision(n).
http://en.cppreference.com/w/cpp/io/manip
You can use the standard streaming mechanic:
streams
You can use ostream to generate the string:
#include <ostream>
#include <sstream>
#include <iomanip>
std::ostringstream stream;
for(...) {
stream << loads[i] << "//";
}
std::string str = stream.str();
The idea is to generate a stream that you can stream strings too. You can then generate a std::string out of it, using stream.str(). Streams have default values for how to convert numbers. You can influence this with std::setprecision and std::fixed as well as other variables (for more info, see the C++ stdlib reference).
Using std::setprecision and std::fixed.
std::ostringstream stream;
// set the precision of the stream to 2 and say we want fixed decimals, not
// scientific or other representations.
stream << std::setprecision(2) << std::fixed;
for(...) {
stream << loads[i] << "//";
}
std::string str = stream.str();
You find another example here.
sprintf
You can always go the C way and use sprintf although it's discouraged as you have to provide a buffer of correct length, e.g.:
char buf[50];
if (snprintf(buf, 50, "%.2f", loads[i]) > 0) {
std::string s(buf);
}

Different values on the function implementation

I'm kind of new with programming and I have wired problem.
I tried to search and read about it, but without success.
I have main file and one class (on windows)
main:
main()
{
LogOut x();
x.WriteToDelayFile(1.2, 3);
}
LogOut class:
void LogOut::WriteToDelayFile(double simTime, int nodeNum)
{
string fileName = "Delay" + nodeNum;
FILE* pFile = OpenFile(fileName);
fputs ("something\n",pFile);
}
I can't figure it out but when I call to WriteToDelayFile(2, 3) with values, I get garbage values edit: (for example, on debug- nodeNum=321546 instead of nodeNum=3) on the LogOut::WriteToDelayFile(double simTime, int nodeNum) implementation
Why does it happen?
Thanks.
As user657267 pointed out in his comment, you may not concatenate a string literal and an int string fileName = "Delay" + nodeNum;. Here you are getting a pointer into the literal, that may even be out of range:
string s = "hello"+1; // leads to "ello" in s
The probably intended concatenation can be done using a stringstream:
#include <sstream>
#include <assert>
void concat_check()
{
std::stringstream ss;
ss << "hello" << 1;
assert(ss.str() == "hello1");
}
Wolf you are a little bit wrong
string s = "hello"+3;
gives "lo" in s data
and
string si = string("hello")+3;
is incorrect you need to use stringstream instead
std::stringstream ss;
ss << "hello" << 3;
std::string s = ss.str();
Dudi Reuveni how can you tell that nodeNum has wrong data?

Easiest way to convert int to string in C++

What is the easiest way to convert from int to equivalent string in C++? I am aware of two methods. Is there an easier way?
(1)
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(2)
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.
#include <string>
std::string s = std::to_string(42);
is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:
auto s = std::to_string(42);
Note: see [string.conversions] (21.5 in n3242)
C++20: std::format would be the idiomatic way now.
C++17:
Picking up a discussion with #v.oddou a couple of years later, C++17 has delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro ugliness.
// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
std::ostringstream sstr;
// fold expression
( sstr << std::dec << ... << args );
return sstr.str();
}
Usage:
int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
C++98:
Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
Usage is as easy as could be:
int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );
The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.
Current C++
Starting with C++11, there's a std::to_string function overloaded for integer types, so you can use code like:
int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);
The standard defines these as being equivalent to doing the conversion with sprintf (using the conversion specifier that matches the supplied type of object, such as %d for int), into a buffer of sufficient size, then creating an std::string of the contents of that buffer.
Old C++
For older (pre-C++11) compilers, probably the most common easy way wraps essentially your second choice into a template that's usually named lexical_cast, such as the one in Boost, so your code looks like this:
int a = 10;
string s = lexical_cast<string>(a);
One nicety of this is that it supports other casts as well (e.g., in the opposite direction works just as well).
Also note that although Boost lexical_cast started out as just writing to a stringstream, then extracting back out of the stream, it now has a couple of additions. First of all, specializations for quite a few types have been added, so for many common types, it's substantially faster than using a stringstream. Second, it now checks the result, so (for example) if you convert from a string to an int, it can throw an exception if the string contains something that couldn't be converted to an int (e.g., 1234 would succeed, but 123abc would throw).
I usually use the following method:
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
It is described in details here.
You can use std::to_string available in C++11 as suggested by Matthieu M.:
std::string s = std::to_string(42);
Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::format_int from the {fmt} library to convert an integer to std::string:
std::string s = fmt::format_int(42).str();
Or a C string:
fmt::format_int f(42);
const char* s = f.c_str();
The latter doesn't do any dynamic memory allocations and is more than 70% faster than libstdc++ implementation of std::to_string on Boost Karma benchmarks. See Converting a hundred million integers to strings per second for more details.
Disclaimer: I'm the author of the {fmt} library.
If you have Boost installed (which you should):
#include <boost/lexical_cast.hpp>
int num = 4;
std::string str = boost::lexical_cast<std::string>(num);
It would be easier using stringstreams:
#include <sstream>
int x = 42; // The integer
string str; // The string
ostringstream temp; // 'temp' as in temporary
temp << x;
str = temp.str(); // str is 'temp' as string
Or make a function:
#include <sstream>
string IntToString(int a)
{
ostringstream temp;
temp << a;
return temp.str();
}
Not that I know of, in pure C++. But a little modification of what you mentioned
string s = string(itoa(a));
should work, and it's pretty short.
sprintf() is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.
Using stringstream for number conversion is dangerous!
See std::ostream::operator<< where it tells that operator<< inserts formatted output.
Depending on your current locale an integer greater than three digits, could convert to a string of four digits, adding an extra thousands separator.
E.g., int = 1000 could be converted to a string 1.001. This could make comparison operations not work at all.
So I would strongly recommend using the std::to_string way. It is easier and does what you expect.
From std::to_string:
C++17 provides std::to_chars as a higher-performance locale-independent alternative.
First include:
#include <string>
#include <sstream>
Second add the method:
template <typename T>
string NumberToString(T pNumber)
{
ostringstream oOStrStream;
oOStrStream << pNumber;
return oOStrStream.str();
}
Use the method like this:
NumberToString(69);
or
int x = 69;
string vStr = NumberToString(x) + " Hello word!."
In C++11 we can use the "to_string()" function to convert an int into a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x = 1612;
string s = to_string(x);
cout << s<< endl;
return 0;
}
C++17 provides std::to_chars as a higher-performance locale-independent alternative.
If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is the example for little-endian architectures (all x86, x86_64 and others):
If you are converting a two-digit number:
int32_t s = 0x3030 | (n/10) | (n%10) << 8;
If you are converting a three-digit number:
int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;
If you are converting a four-digit number:
int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;
And so on up to seven-digit numbers. In this example n is a given integer. After conversion it's string representation can be accessed as (char*)&s:
std::cout << (char*)&s << std::endl;
Note: If you need it on big-endian byte order, though I did not tested it, but here is an example: for three-digit number it is int32_t s = 0x00303030 | (n/100)<< 24 | (n/10%10)<<16 | (n%10)<<8; for four-digit numbers (64 bit arch): int64_t s = 0x0000000030303030 | (n/1000)<<56 | (n/100%10)<<48 | (n/10%10)<<40 | (n%10)<<32; I think it should work.
It's rather easy to add some syntactical sugar that allows one to compose strings on the fly in a stream-like way
#include <string>
#include <sstream>
struct strmake {
std::stringstream s;
template <typename T> strmake& operator << (const T& x) {
s << x; return *this;
}
operator std::string() {return s.str();}
};
Now you may append whatever you want (provided that an operator << (std::ostream& ..) is defined for it) to strmake() and use it in place of an std::string.
Example:
#include <iostream>
int main() {
std::string x =
strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
std::cout << x << std::endl;
}
Use:
#define convertToString(x) #x
int main()
{
convertToString(42); // Returns const char* equivalent of 42
}
int i = 255;
std::string s = std::to_string(i);
In C++, to_string() will create a string object of the integer value by representing the value as a sequence of characters.
I use:
int myint = 0;
long double myLD = 0.0;
string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();
It works on my Windows and Linux g++ compilers.
Here's another easy way to do
char str[100];
sprintf(str, "%d", 101);
string s = str;
sprintf is a well-known one to insert any data into a string of the required format.
You can convert a char * array to a string as shown in the third line.
If you're using MFC, you can use CString:
int a = 10;
CString strA;
strA.Format("%d", a);
C++11 introduced std::to_string() for numeric types:
int n = 123; // Input, signed/unsigned short/int/long/long long/float/double
std::string str = std::to_string(n); // Output, std::string
Use:
#include<iostream>
#include<string>
std::string intToString(int num);
int main()
{
int integer = 4782151;
std::string integerAsStr = intToString(integer);
std::cout << "integer = " << integer << std::endl;
std::cout << "integerAsStr = " << integerAsStr << std::endl;
return 0;
}
std::string intToString(int num)
{
std::string numAsStr;
bool isNegative = num < 0;
if(isNegative) num*=-1;
do
{
char toInsert = (num % 10) + 48;
numAsStr.insert(0, 1, toInsert);
num /= 10;
}while (num);
return isNegative? numAsStr.insert(0, 1, '-') : numAsStr;
}
All you have to do is use String when defining your variable (String intStr). Whenever you need that variable, call whateverFunction(intStr.toInt())
Using the plain standard stdio header, you can cast the integer over sprintf into a buffer, like so:
#include <stdio.h>
int main()
{
int x = 23;
char y[2]; // The output buffer
sprintf(y, "%d", x);
printf("%s", y)
}
Remember to take care of your buffer size according to your needs (the string output size).
string number_to_string(int x) {
if (!x)
return "0";
string s, s2;
while(x) {
s.push_back(x%10 + '0');
x /= 10;
}
reverse(s.begin(), s.end());
return s;
}
This worked for me -
My code:
#include <iostream>
using namespace std;
int main()
{
int n = 32;
string s = to_string(n);
cout << "string: " + s << endl;
return 0;
}
I think using stringstream is pretty easy:
string toString(int n)
{
stringstream ss(n);
ss << n;
return ss.str();
}
int main()
{
int n;
cin >> n;
cout << toString(n) << endl;
return 0;
}
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
namespace std
{
inline string to_string(int _Val)
{ // Convert long long to string
char _Buf[2 * _MAX_INT_DIG];
snprintf(_Buf, "%d", _Val);
return (string(_Buf));
}
}
You can now use to_string(5).
You use a counter type of algorithm to convert to a string. I got this technique from programming Commodore 64 computers. It is also good for game programming.
You take the integer and take each digit that is weighted by powers of 10. So assume the integer is 950.
If the integer equals or is greater than 100,000 then subtract 100,000 and increase the counter in the string at ["000000"];
keep doing it until no more numbers in position 100,000.
Drop another power of ten.
If the integer equals or is greater than 10,000 then subtract 10,000 and increase the counter in the string at ["000000"] + 1 position;
keep doing it until no more numbers in position 10,000.
Drop another power of ten
Repeat the pattern
I know 950 is too small to use as an example, but I hope you get the idea.

How can I check if a number (double type) stored as a string is a valid double number in C++?

I'm having an issue with a program I'm working on in C++. I am asking the user to input a valid number. I take it in as a string because the particular assignment I'm doing, it makes it easier in the long run. For basic error checking, I want to check to see if the number entered is a valid number. Example:
Enter number: 3.14
This would be valid
Enter number: 3.1456.365.12
This shouldn't be valid
use strtod, which converts a string to a double and returns any characters it couldn't interpret as part of the double.
double strtod(const char* nptr, char** endptr)
Like this:
char* input = "3.1456.365.12";
char* end;
strtod(input, &end);
if (*input == '\0')
{
printf("fail due to empty string\n");
}
if (end == input || *end != '\0')
{
printf("fail - the following characters are not part of a double\n%s\n", end);
}
I think boost::lexical_cast should help you here
An example using only standard C++:
#include <sstream>
// ...
double dbl = 0.0;
std::istringstream num("3.1456.365.12");
num >> dbl;
if(!num.fail() &&
num.eof()) // This second test is important! This makes sure that the entire string was converted to a number
{
// success
}
else
{
// failure
}
Bonus generic template function version:
#include <sstream>
#include <string>
#include <exception>
// Version that throws an exception on a bad parse:
template <typename T>
T parse(const std::string& str)
{
T value;
std::istringstream parser(str);
parser >> value;
if(!parser.fail() && parser.eof())
{
return value;
}
else
{
throw "bad lexical cast";
}
}
// usage:
double foo = parse<double>("3.14234");
// Non-exception, error code version
template <typename T>
bool parse(const std::string& str, T& value)
{
std::istringstream parser(str);
parser >> value;
return (!parser.fail() && parser.eof());
}
// usage:
double foo = 0.0;
bool success = parser<double>("3.11234", foo);
If you have no boost, you always can use strtod
You can use strtoX (where X is f for float, l for long, ul for unsigned long, etc.), choosing for the kind of number you want. One of the parameters you give it is an "end pointer", which points to the first character in the string that could not be converted into the target number type.
In your case, what you're apparently looking for is that the end pointer should be at the end of the string, indicating that all characters in the string were converted to the target type.
Edit: Sorry, didn't notice that you'd mentioned 'double' in the title (but not the question itself). That being the case, you'd use strtod, as a couple of others have also advised.
The best way is to make an actual attempt to convert your string to double using any of the standard and/or idiomatic ways to do the conversion, and check for errors afterwards. In C that would be functions from strto... group (which are, of course, perfectly usable in C++ as well). In C++ you can use stream-based conversion idiom.
One thing to watch for though is that the common convention in standard conversion methods is to convert "as much as possible" and not consider any extra characters as an error. For example, a string "123abc" is normally considered valid input, with only "123" part getting converted. All usable methods provide you with the way to detect the fact that there is something extra after the actual number, if you want to treat this situation as an error. But it is up to you to take the additional steps to perform this verification.
A simple option is to use the sscanf function:
const char * num_as_str = "3.1416";
double num;
if(std::sscanf(num_as_str, "%lg", &num) == 1)
{
std::cout << "You correctly entered the number " << num << "\n";
}
If you want to get fancy you can use istringstream:
std::istringstream iss(num_as_str);
if(iss >> num)
{
std::cout << "You correctly entered the number " << num << "\n";
}
If you want to get extra-fancy you can use boost's lexical_cast:
try
{
num = boost::lexical_cast<double>(num_as_str);
}
catch(boost::bad_lexical_cast &)
{
std::cout << "What you entered is not a proper number" << num << "\n";
}
Ah, I loved these assignments. A good old hand written lexer is the way to go (since you are still in the begining days -- don't try to use boost just yet). They are fast, easy to write and extremely fun to play with. If you can get a copy of Levine's book on Lex/Yacc, look up the first couple of chapters for ideas.
As mentioned by AndreyT, the best way is to attempt to convert the string into a float and check for an error. Personally I would opt to use std::istringstream, as you're using C++. Something like the following should work:
float ff;
std::istringstream istr;
std::string input("1234.5678");
// set the stream to have your string as its base
istr.str(input);
// now try to read the number:
istr >> ff;
if (istr.fail())
{
// some error in the parsing
}
istringstream is part of STL, so you shouldn't need any additional libraries, and it will also with with exceptions if that's your choice. More information can be found here: http://www.cplusplus.com/reference/iostream/istringstream/
You could use regular expressions. Since you already have a string, it would be easy to compare that with this regex:
/^\d+(\.\d+)?$/
The library regex.h can help you here. See this: regex.h
This is my quick hack :)
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <typename T>
bool fromStr(const std::string& str, T& var)
{
std::stringstream convertor;
convertor << str;
convertor >> var;
if( convertor.fail() )
return false;
char c = static_cast<char>( convertor.get() );
return convertor.eof() || c == '\n' || c == ' ' || c == '\t';
}
int main()
{
double d;
std::string str = "5.04146.55";
if( fromStr<double>(str, d) )
{
std::cout << "Valid conversion!, d = " << d;
}
else
{
std::cout << "Invalid conversion!";
}
}