I had a question when providing an API
if I ask for them to give me a _int64 10 digit hexadecimal number but my function internally takes strings how do I effectively convert that...
as of right now I was just using string internally but for compatibility reasons i was using char* c style so that give any system 32 or 64 it wouldn't matter. Is that the accurate thing to do? or am i wrong?
is there a problem using char* vs _int64?
C++11 standardized the std::to_string function:
#include <string>
int main()
{
int64_t value = 128;
std::string asString = std::to_string(value);
return 0;
}
#include <string>
#include <sstream>
int main()
{
std::stringstream stream;
__int64 value(1000000000);
stream << value;
std::string strValue(stream.str());
return 0;
}
The best option is to change the function to not use strings anymore so you can pass the original __int64 as-is. __int64 works the same in 32-bit and 64-bit systems.
If you have to convert to a string, there are several options. Steve showed you how to use a stringstream, which is the C++ way to do it. You can also use the C sprintf() or _i64toa() functions:
__int64 value = ...;
char buffer[20];
sprintf(buffer, "%Ld", value);
__int64 value = ...;
char buffer[20];
_i64toa(value, buffer, 10);
Related
This question already has answers here:
How to convert a number to string and vice versa in C++
(5 answers)
Closed 9 years ago.
#include <iostream>
using namespace std;
int main() {
string a = "1234"; //How this string convert in integer number
system("pause");
return EXIT_SUCCESS;
}
string a = "1234";
How this convert in integer
You can use std::stoi() to convert a std::string to an int.
#include <iostream>
#include <string>
int main() {
std::string a = "1234"; //How this string convert in integer number
int b = std::stoi(a);
system("pause");
return EXIT_SUCCESS;
}
If you have C++11 and onwards, use
int n = std::stoi(a);
(Pre C++11, you could use std::strtol;)
You could use boosts lexical cast
#include <boost/lexical_cast.hpp>
std::string str_num = "12345";
int value = 0;
try
{
value = boost::lexical_cast<int>(str_num);
}
catch(boost::bad_lexical_cast &)
{
// error with conversion - calling code will deal with
}
This way you can easily modify the code to deal with float or double if your string contains those types of numeric value also
You have to use std::stoi:
#include <iostream>
#include <string>
std::string s = "123";
int number= std::stoi(s);
The C++ Standard has a special function
int stoi(const string& str, size_t *idx = 0, int base = 10);
Probably you can try this
string a = "28787" ;
int myNumber;
istringstream ( a) >> myNumber;
See or you can search for stoi function and see how it can be used. Probably It can work but never try because I dont have the compiler of c++
here i have code for calculate hash value of unsigned char
#include <cstdlib>
#include <iostream>
#include<string.h>
using namespace std;
unsigned oat_hash(unsigned char *key,int len)
{
unsigned char *p=key;
unsigned h=0;
int i;
for(i=0;i<len;++i){
h+=p[i];
h+=(h<<10);
h^=(h>>6);
}
h+=(h<<3);
h^=(h>>11);
h+=(h<<15);
return h;
}
using namespace std;
int main(int argc, char *argv[])
{
unsigned char mystring[]="123456789abcdef";
unsigned char *key=&mystring[0];
int n=sizeof(mystring)/sizeof(mystring[0]);//length of mystring
cout<<oat_hash(key,n)<<endl;
//system("PAUSE");
//return EXIT_SUCCESS;
return 0;
}
name of this hash function is so called One-at-a-Time hash(by Bob Jenkins) i have one question is this little part of code correct?
int n=sizeof(mystring)/sizeof(mystring[0]);//length of mystring
because mysting has not built-in function length,i used this
Under the circumstances, yes -- but it's pretty fragile. For example, if you changed your definition from:
unsigned char mystring[]="123456789abcdef";
To:
unsigned char *mystring="123456789abcdef";
Your method of finding the length would produce completely incorrect results. Also note that since your string is made up of chars, the /sizeof(mystring[0]) isn't really necessary either -- sizof(char) == 1 (and the same for signed char or unsigned char).
You normally want to use strlen instead.
Yeah, your code is correct. You may want to compare against the data-type though:
int n=sizeof(mystring) / sizeof(char); //length of mystring
Note that this only works if the string isn't dynamic.
Otherwise use strlen for c-style strings.
I must say, however, C++'s std::string does have a length method, and is much easier to use in the majority of cases - especially when using them with the STL.
Also, boost can do C++ string hashes
Yes I feel that the code will work fine. But ensure that if you pass an array of a string through a method it would not give you the desired result since passing array in functions implicitly passed by a pointer. That time your code can provide a disaster. Other wise it is fine. The other way you can find the length of a string array is like:
int len = 0;
int iCount = 0;
while (mystring[iCount].empty() != true)
{
iCount++;
len++;
}
Then use len as length of the String array
Hope this will help.
Since this question gets asked about every week, this FAQ might help a lot of users.
How to convert an integer to a string in C++
how to convert a string into an integer in C++
how to convert a floating-point number to a string in C++
how to convert a string to a floating-point number in C++
Update for C++11
As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).
string to numeric
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument or std::out_of_range).
If conversion succeeded and idx is not 0, idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.
Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10 until z=35). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.
Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.
numeric to string
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.
As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.
There are also similar functions defined that are named to_wstring, these will return a std::wstring.
How to convert a number to a string in C++03
Do not use the itoa or itof functions because they are non-standard and therefore not portable.
Use string streams
#include <sstream> //include this to use string streams
#include <string>
int main()
{
int number = 1234;
std::ostringstream ostr; //output string stream
ostr << number; //use the string stream just like cout,
//except the stream prints not to stdout but to a string.
std::string theNumberString = ostr.str(); //the str() function of the stream
//returns the string.
//now theNumberString is "1234"
}
Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with cout
std::ostringstream ostr;
float f = 1.2;
int i = 3;
ostr << f << " + " i << " = " << f + i;
std::string s = ostr.str();
//now s is "1.2 + 3 = 4.2"
You can use stream manipulators, such as std::endl, std::hex and functions std::setw(), std::setprecision() etc. with string streams in exactly the same manner as with cout
Do not confuse std::ostringstream with std::ostrstream. The latter is deprecated
Use boost lexical cast. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. To download and install boost and its documentation go here. Although boost isn't in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.
Lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
float f = 1.2;
int i = 42;
std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
}
How to convert a string to a number in C++03
The most lightweight option, inherited from C, is the functions atoi (for integers (alphabetical to integer)) and atof (for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.
#include <cstdlib> //the standard C library header
#include <string>
int main()
{
std::string si = "12";
std::string sf = "1.2";
int i = atoi(si.c_str()); //the c_str() function "converts"
double f = atof(sf.c_str()); //std::string to const char*
}
Use string streams (this time input string stream, istringstream). Again, istringstream is used just like cin. Again, do not confuse istringstream with istrstream. The latter is deprecated.
#include <sstream>
#include <string>
int main()
{
std::string inputString = "1234 12.3 44";
std::istringstream istr(inputString);
int i1, i2;
float f;
istr >> i1 >> f >> i2;
//i1 is 1234, f is 12.3, i2 is 44
}
Use boost lexical cast.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
std::string sf = "42.2";
std::string si = "42";
float f = boost::lexical_cast<float>(sf); //f is 42.2
int i = boost::lexical_cast<int>(si); //i is 42
}
In case of a bad input, lexical_cast throws an exception of type boost::bad_lexical_cast
In C++17, new functions std::to_chars and std::from_chars are introduced in header charconv.
std::to_chars is locale-independent, non-allocating,
and non-throwing.
Only a small subset of formatting policies used by
other libraries (such as std::sprintf) is provided.
From std::to_chars, same for std::from_chars.
The guarantee that std::from_chars can recover
every floating-point value formatted
by to_chars exactly is only provided if both
functions are from the same implementation
// See en.cppreference.com for more information, including format control.
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <charconv>
using Type = /* Any fundamental type */ ;
std::size_t buffer_size = /* ... */ ;
[[noreturn]] void report_and_exit(int ret, const char *output) noexcept
{
std::printf("%s\n", output);
std::exit(ret);
}
void check(const std::errc &ec) noexcept
{
if (ec == std::errc::value_too_large)
report_and_exit(1, "Failed");
}
int main() {
char buffer[buffer_size];
Type val_to_be_converted, result_of_converted_back;
auto result1 = std::to_chars(buffer, buffer + buffer_size, val_to_be_converted);
check(result1.ec);
*result1.ptr = '\0';
auto result2 = std::from_chars(buffer, result1.ptr, result_of_converted_back);
check(result2.ec);
assert(val_to_be_converted == result_of_converted_back);
report_and_exit(0, buffer);
}
Although it's not fully implemented by compilers, it definitely will be implemented.
I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:
// make_string
class make_string {
public:
template <typename T>
make_string& operator<<( T const & val ) {
buffer_ << val;
return *this;
}
operator std::string() const {
return buffer_.str();
}
private:
std::ostringstream buffer_;
};
And then you use it as;
string str = make_string() << 6 << 8 << "hello";
Quite nifty!
Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number;
(and its not as clever as the last one either)
// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
std::stringstream buf;
buf << str;
RETURN_TYPE val;
buf >> val;
return val;
}
Use as:
int x = parse_string<int>("78");
You might also want versions for wstrings.
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string s="000101";
cout<<s<<"\n";
int a = stoi(s);
cout<<a<<"\n";
s=to_string(a);
s+='1';
cout<<s;
return 0;
}
Output:
000101
101
1011
I changed my class to use std::string (based on the answer I got here but a function I have returns wchar_t *. How do I convert it to std::string?
I tried this:
std::string test = args.OptionArg();
but it says error C2440: 'initializing' : cannot convert from 'wchar_t *' to 'std::basic_string<_Elem,_Traits,_Ax>'
std::wstring ws( args.OptionArg() );
std::string test( ws.begin(), ws.end() );
You can convert a wide char string to an ASCII string using the following function:
#include <locale>
#include <sstream>
#include <string>
std::string ToNarrow( const wchar_t *s, char dfault = '?',
const std::locale& loc = std::locale() )
{
std::ostringstream stm;
while( *s != L'\0' ) {
stm << std::use_facet< std::ctype<wchar_t> >( loc ).narrow( *s++, dfault );
}
return stm.str();
}
Be aware that this will just replace any wide character for which an equivalent ASCII character doesn't exist with the dfault parameter; it doesn't convert from UTF-16 to UTF-8. If you want to convert to UTF-8 use a library such as ICU.
This is an old question, but if it's the case you're not really seeking conversions but rather using the TCHAR stuff from Mircosoft to be able to build both ASCII and Unicode, you could recall that std::string is really
typedef std::basic_string<char> string
So we could define our own typedef, say
#include <string>
namespace magic {
typedef std::basic_string<TCHAR> string;
}
Then you could use magic::string with TCHAR, LPCTSTR, and so forth
It's rather disappointing that none of the answers given to this old question addresses the problem of converting wide strings into UTF-8 strings, which is important in non-English environments.
Here's an example code that works and may be used as a hint to construct custom converters. It is based on an example code from Example code in cppreference.com.
#include <iostream>
#include <clocale>
#include <string>
#include <cstdlib>
#include <array>
std::string convert(const std::wstring& wstr)
{
const int BUFF_SIZE = 7;
if (MB_CUR_MAX >= BUFF_SIZE) throw std::invalid_argument("BUFF_SIZE too small");
std::string result;
bool shifts = std::wctomb(nullptr, 0); // reset the conversion state
for (const wchar_t wc : wstr)
{
std::array<char, BUFF_SIZE> buffer;
const int ret = std::wctomb(buffer.data(), wc);
if (ret < 0) throw std::invalid_argument("inconvertible wide characters in the current locale");
buffer[ret] = '\0'; // make 'buffer' contain a C-style string
result = result + std::string(buffer.data());
}
return result;
}
int main()
{
auto loc = std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8
if (loc == nullptr) throw std::logic_error("failed to set locale");
std::wstring wstr = L"aąß水𝄋-扫描-€𐍈\u00df\u6c34\U0001d10b";
std::cout << convert(wstr) << "\n";
}
This prints, as expected:
Explanation
7 seems to be the minimal secure value of the buffer size, BUFF_SIZE. This includes 4 as the maximum number of UTF-8 bytes encoding a single character; 2 for the possible "shift sequence", 1 for the trailing '\0'.
MB_CUR_MAX is a run-time variable, so static_assert is not usable here
Each wide character is translated into its char representation using std::wctomb
This conversion makes sense only if the current locale allows multi-byte representations of a character
For this to work, the application needs to set the proper locale. en_US.utf8 seems to be sufficiently universal (available on most machines). In Linux, available locales can be queried in the console via locale -a command.
Critique of the most upvoted answer
The most upvoted answer,
std::wstring ws( args.OptionArg() );
std::string test( ws.begin(), ws.end() );
works well only when the wide characters represent ASCII characters - but these are not what wide characters were designed for. In this solution, the converted string contains one char per each source wide char, ws.size() == test.size(). Thus, it loses information from the original wstring and produces strings that cannot be interpreted as proper UTF-8 sequences. For example, on my machine the string resulting from this simplistic conversion of "ĄŚĆII" prints as "ZII", even though its size is 5 (and should be 8).
You could just use wstring and keep everything in Unicode
just for fun :-):
const wchar_t* val = L"hello mfc";
std::string test((LPCTSTR)CString(val));
Following code is more concise:
wchar_t wstr[500];
char string[500];
sprintf(string,"%ls",wstr);
How do I convert a long to a string in C++?
In C++11, there are actually std::to_string and std::to_wstring functions in <string>.
string to_string(int val);
string to_string(long val);
string to_string(long long val);
string to_string(unsigned val);
string to_string(unsigned long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string (long double val);
You could use stringstream.
#include <sstream>
// ...
std::string number;
std::stringstream strstream;
strstream << 1L;
strstream >> number;
There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though.
The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf_s which protects against buffer overruns.
Well if you are fan of copy-paste, here it is:
#include <sstream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
boost::lexical_cast<std::string>(my_long)
more here http://www.boost.org/doc/libs/1_39_0/libs/conversion/lexical_cast.htm
You can use std::to_string in C++11
long val = 12345;
std::string my_val = std::to_string(val);
int main()
{
long mylong = 123456789;
string mystring;
stringstream mystream;
mystream << mylong;
mystring = mystream.str();
cout << mystring << "\n";
return 0;
}
I don't know what kind of homework this is, but most probably the teacher doesn't want an answer where you just call a "magical" existing function (even though that's the recommended way to do it), but he wants to see if you can implement this by your own.
Back in the days, my teacher used to say something like "I want to see if you can program by yourself, not if you can find it in the system." Well, how wrong he was ;) ..
Anyway, if your teacher is the same, here is the hard way to do it..
std::string LongToString(long value)
{
std::string output;
std::string sign;
if(value < 0)
{
sign + "-";
value = -value;
}
while(output.empty() || (value > 0))
{
output.push_front(value % 10 + '0')
value /= 10;
}
return sign + output;
}
You could argue that using std::string is not "the hard way", but I guess what counts in the actual agorithm.
There are several ways. Read The String Formatters of Manor Farm for an in-depth comparison.
#include <sstream>
....
std::stringstream ss;
ss << a_long_int; // or any other type
std::string result=ss.str(); // use .str() to get a string back
Check out std::stringstream.
One of the things not covered by anybody so far, to help you think about the problem further, is what format should a long take when it is cast to a string.
Just have a look at a spreedsheet program (like Calc/Excel). Do you want it rounded to the nearest million, with brackets if it's negative, always to show the sign.... Is the number realy a representation of something else, should you show it in Oractal or Hex instead?
The answers so far have given you some default output, but perhaps not the right ones.
The way I typically do it is with sprintf. So for a long you could do the following assuming that you are on a 32 bit architecture:
char buf[5] = {0}; // one extra byte for null
sprintf(buf, "%l", var_for_long);