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

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.

Related

How to deal with garbage characters in a string?

Suppose I have a string that contains a necessary numeric character but it is not terminated by '/0', it has garbage characters instead. Actually, the string has garbage characters after the number. So how to deal with the garbage character while storing that numerical character in another string or variable?
So how to deal with the garbage character while storing that numerical character in another string or variable?
Only copy a substring. Example:
std::string example "garbage1garbage";
char numerical = example[7];
We got the numerical character excluding the garbage entirely.
If the text be converted is in a std::string, then you can extract a number from the front as follows:
#include <sstream>
...
std::string input = "128734garbage";
std::istringstream iss{input};
int num;
if (iss >> num)
...use_num...
else
std::cerr << "wasn't able to parse an int from input\n";
Just change int to double, uint64_t, ... - whatever suits your data.
If you have only a pointer to the text and know it's not null-terminated, just getting the text into a std::string is problematic. You could instead use a function that converts text to a number, but stops at the first invalid character. std::stol et al, and the other unsigned and floating point variants linked from the same reference page, are good candidates for that.
From your "another string or variable" - the above addresses storing into a numeric variable. You can then create a new std::string from the number using std::to_string, or a std::ostringstream, if that's what you want to do. This will standardise the output format though, so input like say "1E4" might end up looking like say 1000.0. Alternatively, with the stol-type functions you can use the pointer-to-the-end-of-the-number to work out the length of the numeric part, and use std::string::substr() to extract the leading number as a new std::string object.
You should also be aware that the distinction between number and garbage is not always what you might expect. For example "0XBEFHJQ" might be split by some of the above functions as 0xBEF hex and HJQ garbage.

Converting integer to string in c++

This is the code I wrote to convert integer to string.
#include <iostream>
using namespace std;
int main()
{
string s;
int b=5;
s.push_back((char)b);
cout<<s<<endl;
}
I expected the output to be 5 but it is giving me blank space.
I know there is another way of doing it using stringstream but I want to know what is wrong in this method?
Character code for numbers are not equal to the integer the character represents in typical system.
It is granteed that character codes for decimal digits are consecutive (N3337 2.3 Character sets, Paragraph 3), so you can add '0' to convert one-digit number to character.
#include <iostream>
using namespace std;
int main()
{
string s;
int b=5;
s.push_back((char)(b + '0'));
cout<<s<<endl;
}
You are interpreting the integer 5 as a character. In ASCII encoding, 5 is the Enquiry control character as you lookup here.
The character 5 on the other hand is represented by the decimal number 53.
As others said, you can't convert an integer to a string the way you are doing it.
IMHO, the best way to do it is using the C++11 method std::to_string.
Your example would translate to:
using namespace std;
int main()
{
string s;
int b=5;
s = to_string(b);
cout<<s<<endl;
}
The problem in your code is that you are converting the integer 5 to ASCII (=> ENQ ASCII code, which is not "printable").
To convert it to ASCII properly, you have to add the ASCII code of '0' (48), so:
char ascii = b + '0';
However, to convert an integer to std::string use:
std::stringstream ss; //from <sstream>
ss << 5;
std::string s = ss.str ();
I always use this helper function in my projects:
template <typename T>
std::string toString (T arg)
{
std::stringstream ss;
ss << arg;
return ss.str ();
}
Also, you can use stringstream,
std::to_string doesn't work for me on GCC
If we were writing C++ from scratch in 2016, maybe we would make this work. However as it choose to be (mostly) backward compatible with a fairly low level language like C, 'char' is in fact just a number, that string/printing algorithms interpret as a character -but most of the language doesn't treat special. Including the cast. So by doing (char) you're only converting a 32 bit signed number (int) to a 8 bit signed number (char).
Then you interpret it as a character when you print it, since printing functions do treat it special. But the value it gets printed to is not '5'. The correspondence is conventional and completely arbitrary; the first numbers were reserved to special codes which are probably obsolete by now. As Hoffman pointed out, the bit value 5 is the code for Enquiry (whatever it means), while to print '5' the character has to contain the value 53. To print a proper space you'd need to enter 32. It has no meaning other than someone decided this was as good as anything, sometime decades ago, and the convention stuck.
If you need to know for other characters and values, what you need is an "ASCII table". Just google it, you'll find plenty.
You'll notice that numbers and letters of the same case are next to each other in the order you expect, so there is some logic to it at least. Beware, however, it's often not intuitive anyway: uppercase letters are before lowercase ones for instance, so 'A' < 'a'.
I guess you're starting to see why it's better to rely on dedicated system functions for strings!

converting to convert a string to double with limitation

I'm using c++ and I'm trying to convert a string to double, the string is given to me as an input in the form: "xx.yy", and it should stay that way, meaning no more than two digits after the dot.
I've tried atof and strod but outcome was no good, plus i can't use anything to spectacular' because it's for a course and no one will belive me
str_db = strtod(ptr, NULL);
item->price = str_db;
str_db is type double.
Thank you.

Extracting a double from a string with text [duplicate]

This question already has an answer here:
std::stringstream strange behaviour
(1 answer)
Closed 9 years ago.
I have a string with lots of different characters similar to: "$: " "213.23453"
How do i extract the double value 213.23453 and store it in a variable, it's C++/C and i cant use lambdas.
You can use "poor man's regex" of the sscanf function to skip over the characters prior to the first digit, and then reading the double, like this:
char *str = "\"$: \" \"213.23453\"";
double d;
sscanf(str, "%*[^0-9]%lf", &d);
Note the asterisk after the first percentage format: it instructs sscanf to read the string without writing its content into an output buffer.
Here is a demo on ideone.
Use a regular expression.
[$]?[0-9]*(\.)?[0-9]?[0-9]?
This should match those with a $ sign and those without.
Boost.Regex is a very good regular expression library
Personally, I find Boost.Xpressive much nicer to work with. It is a header-only library and it has some nice features such as static regexes (regexes compiled at compile time).
If you're using a C++11 compliant compiler, use std::regex unless you have good reason to use something else.
Pure C++ solution could be to manually cut off the trash characters preceding the number (first digit identified by std::isdigit) and then just construct a temporary istringstream object to retrieve the double from:
std::string myStr("$:. :$$#&*$ :213.23453$:#$;");
// find the first digit:
int startPos = 0;
for (; startPos < myStr.size(); ++startPos)
if (std::isdigit(myStr[startPos])) break;
// cut off the trash:
myStr = myStr.substr(startPos, myStr.size() - startPos);
// retrieve the value:
double d;
std::istringstream(myStr) >> d;
but C-style sscanf with appropriate format specified would suffice here as well :)

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?