How to convert string to int with different bases? - c++

I want to convert string to int but the conversion has to consider the prefixes 0x or 0 if any and consider the input as hex or oct respectively. Using istringstream, you need to explicitly specify the base. Is there any way than explicitly coding to check for characters 0x?
Edit:
The conversion should implicitly find the base based on the prefix. Just like int i = 0x123; does.

You can use the std::stoi family of functions from C++11.

You can use C function strtol : http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/
It understands 0x/0 prefices.

Related

How to convert opcua string to standard string in c++

can someone tell how to convert UaString to std::string in c++.
There is already a question which converts std::string to uastring:
How can i convert a std::string to UaString?
Thanks in advance!
e.g. You have UaString as below:
UaString sString("Test String");
Then you can make standard string as,
std::string myString(sString.toUtf8());
Reference:
UA Server SDK C++
C++ String Class
One way could be to use the toUtf8 member function which returns a const char* that can be used to construct a std::string.
std::string str(uastring.toUtf8());
An alternative if uastring may contain null terminators:
std::string str(uastring.toUtf8(), uastring.size());
Note that UaString::length() shouldn't be used in this case since it returns the number of UTF8 characters while UaString::size() returns the number of bytes (which may be greater).

c++ how to convert char to int while using `tolower`

I'm try to compile a simple expression:
char_to_int(tolower(row[y]))
However I'm getting the following errors when trying to compile it:
error: implicit conversion loses integer precision: 'int' to 'char' [-Werror,-Wimplicit-int-conversion]
if (char_to_int(tolower(row[y])) > n
The signature of char_to_int is:
unsigned long char_to_int(char c)
and the type of row[y] is char.
Why am I getting this error and how can I fix it?
From your error information I assume you are using std::tolower from <cctype> (or equivalently, ::tolower from <ctype.h>), not std::tolower from <locale>.
Why you are getting the error is straightforward from your error information: your char_to_int expects a char, but tolower returns an int. This will cause loss of information.
Why does tolower return an int, not just a char? Because it can accept and return EOF, which may fall out of range of any char.
The fix can be straightforward: change your char_to_int to accept int, or do an intermediate step to discard the possible EOF.
std::tolower doesn't actually operate on chars: it operates on ints! Moreover, there is risk of undefined behaviour: if on your machine char is a signed type, then the "negative" characters will correspond to negative integers, which std::tolower is not equipped to deal with.
A way to fix this for your use is to manually cast the types before use:
char_to_int(static_cast<char>(
std::tolower(static_cast<unsigned char>(row[y]))));
... which unfortunately is a bit of a mess, but that's what you have to do.
Alternatively, you may use the locale version of std::tolower, which is templated and will correctly handle char types. You may use it like so:
// std::locale{} is an object representing the default locale
// you may specify a locale precisely if needed; see the above links
char_to_int(std::tolower(row[y], std::locale{}));
tolower returns an int. std::tolower is however a template, and will work correctly for char. In general, if there is a std:: version of any func you are calling, use it! :)

C++, how to get right double value from string?

Or which type do I need to use?
I have string and I try to convert it into double
NFR_File.ReadString(sVal); // sVal = " 0,00003"
dbl = _wtof(sVal);
and get:
3.0000000000000001e-05
And I need 0,00003, because then I should write it into the file as "0,00003" but not as 3e-05.
If the number greater then 0,0009 everything works.
displaying:
sOutput.Format(_T("%9g"),dbl);
NFP1_File.WriteString(sOutput);
I need it without trailing zeros and also reserve 9 digits (with spaces)
When you write using printf you can specify the number of significant digits you want by using the .[decimals]lf.
For example, in your case you want to print with 5 decimals, so you should use
printf("%.5f", yourNumber);
If you can use C++11
try use http://en.cppreference.com/w/cpp/string/basic_string/to_string
std::string to_string( double value );
CString::Format
Call this member function to write formatted data to a CString in the same way that sprintf formats data into a C-style character array.
It is same as c sprintf format. You may check other answer's format usage.

Char to Int in C++? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to convert a single char into an int
Well, I'm doing a basic program, wich handles some input like:
2+2
So, I need to add 2 + 2.
I did something like:
string mys "2+2";
fir = mys[0];
sec = mys[2];
But now I want to add "fir" to "sec", so I need to convert them to Int.
I tried "int(fir)" but didn't worked.
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
Alright so first a little backround on why what you attempted didn't work. In your example, fir is declared as a string. When you attempted to do int(fir), which is the same as (int)fir, you attempted a c-style cast from a string to an integer. Essentially you will get garbage because a c-style cast in c++ will run through all of the available casts and take the first one that works. At best your going to get the memory value that represents the character 2, which is dependent upon the character encoding your using (UTF-8, ascii etc...). For instance, if fir contained "2", then you might possibly get 0x32 as your integer value (assuming ascii). You should really never use c-style casts, and the only place where it's really safe to use them are conversions between numeric types.
If your given a string like the one in your example, first you should separate the string into the relevant sequences of characters (tokens) using a function like strtok. In this simple example that would be "2", "+" and "2". Once you've done that you can simple call a function such as atoi on the strings you want converted to integers.
Example:
string str = "2";
int i = atoi(str.c_str()); //value of 2
However, this will get slightly more complicated if you want to be able to handle non-integer numbers as well. In that case, your best bet is to separate on the operand (+ - / * etc), and then do a find on the numeric strings for a decimal point. If you find one you can treat it as a double and use the function atof instead of atoi, and if you don't, just stick with atoi.
Have you tried atoi or boost lexical cast?

Cast a pointer to char to a double C++

How can i cast a pointer to char to a double ?
I am using command line arguments and one of the argument is a double but in the program is it passed as a char*.
I tried using static_cast and reinterpret_cast but with no effect.
Pure C++ solution:
#include <sstream>
// ...
std::stringstream ss;
ss << your_char_pointer;
ss >> your_double;
Boost solution:
#include <boost/lexical_cast.hpp>
// ...
your_double = boost::lexical_cast<double>(your_char_pointer);
Try Boost lexical_cast.
double val = atof(*charpointer)
atof stands for "all to float", (or "array to float"), and does exactly what you want. If it cannot convert the char array, it returns 0.0. See: Man atof
That's not how type conversion in C/C++ works. You must pass the string through a numeric parser manually. E.g.
char *thestring;
double d;
d = atof(thestring);
If the double comes from the command line, it is actually a real string, you have to convert it to a double, you can't just cast it.
For example, you can use strtod for this task :
double d = strtod (mystr,NULL);
You're trying to convert a string (represented by the char *) into a double. This is not something you can do with a regular built in type cast in C++ as all they do is reinterpret the bit pattern that is being referenced by the pointer. Instead you have to parse the command line argument to extract a double value from the string.
As mentioned, you have several options:
you can use atof for the conversion, but it's hard to determine if the conversion errored because both a string that can't be converted and one representing 0.0 give you the same result
As Fred Larson mentioned, you can use boost::lexical_cast. That's a pretty elegant way to handle the problem and would most likely be my preferred one
You can use iostreams to do the conversion
You can write the conversion code yourself (just kidding)
The atof man page says "The atof() function has been deprecated by strtod() and should not be used in new code."