Convert CString to float in mfc - c++

how can I convert a CString variable to a floating point?
(I'm using visuall c++ 6.0 and the MFC)
I'm trying to use an edit box to return a value which I'm putting into an array of floating points. I'm Using the GetWindowText method to get the value, which returns a CString. So I need to convert to a floating point. (or am I just doing things completely the wrong way?).
I presume there are methods for doing this already in the MFC.(have already used the Format method to convet to a CString display the values in the array in the edit box)
Thanks.

you can just do
CString pi = "3.14";
return atof(pi);
EDIT
Also use this function:
CString pi = "3.14";
return _ttof(pi);
Reading a string value and parse/convert it to float allows you to locate the error when there is one. All you need is a help of a C Run-time function: strtod() or atof().
I would prefer strtod as the second argument returns a pointer to the string where the parse terminated:
CString str;
m_edtMyEditBox.GetWindowText(str);
char *pEnd;
double dValue = strtod(str.GetBuffer(str.GetLength()), &pEnd);
if (*pEnd != '\0')
{
// Error in parsing
}
str.ReleaseBuffer();

Related

How to work with wxString, numbers and other string types in wxWidgets

As I startded programming in C++ with wxWidgets (in code::blocks), I often had the issue that I did not know how to use wxString in a good way. The main reason was that there are already several string types in C++ and wxWidgets now adds another. I already had some classes imported from another project without wxWidgets, so now everything needed to be compatible.
This lead to several questions:
How to convert wxString to another string type?
How to convert another string type to wxString?
How to convert an integer number to wxString?
How to convert a wxString to an integer number?
How to convert a floating point number to wxString?
How to convert a wxString to a floating point number?
First of all, there is this helpfull site in the wxWidgets wiki on how to deal with wxStrings. I will partly quote it, though in my opinion it is not as detailed as I would have needed it, this is why I created this Q&A.
How to convert wxString to another string type?
For C style strings, I use this method:
wxString fileName = "myFile";
const char* fileNameChar = fileName.mb_str();
To convert wxString to std::string use (as the website says):
wxWidgets 2.8 :
wxString mystring(wxT("HelloWorld"));
std::string stlstring = std::string(mystring.mb_str());
Under wxWidgets 3.0, you may use
wxString::ToStdString()
And for std::wstring under wxWidgets 3.0, you may use
wxString myString = "abc";
std::wstring myWString = wxString::ToStdWstring(myString);
(not tested, documented here).
How to convert from another string type?
To convert from C style strings use:
const char* fileNameChar = "myFile";
wxString fileName(fileNameChar);
For std::strings either
std::string fileNameStd = "myFile";
wxString fileName(fileNameStd.c_str());
or (from wxWidgets 3.0)
wxString fileName(fileNameStd);
And for std::wstring:
Starting from wxWidgets 3.0, you may use the appropriate constructor
std::wstring stlstring = L"Hello world";
// assuming your string is encoded as the current locale encoding (wxConvLibc)
wxString mystring(stlstring);
How to convert an integer number to wxString?
You can either use
int number = 3;
wxString myString = wxString::Format(wxT("%i"), number);
or
#include <wx/numformatter.h>
int number = 3;
wxString myString = wxNumberFormatter::ToString(number);
The second method is documented here. You don't have to use the flag and you can use not only long as it is in the documentation, but other integer types as well (as I did here with int).
How to convert wxString to an integer number?
I always use this method:
wxString numberString = "12345";
int number = wxAtoi(numberString);
How to convert a floating point number to wxString?
You can use the first method if you don't need to set the accurracy of your floating point values (normal accurracy is 6 numbers after the comma)
double doubleNumber = 12.3455;
wxString numberString = wxString::Format(wxT("%f"), doubleNumber);
Be carefull, as it is "%f" no matter if you want to convert a double or a float number. If you try to use "%d" instead your program will crash. If you use this method to convert anything that has more than 6 digits after the comma, it will be cut.
If you need a given accurracy, you can use this function
#include <wx/numformatter.h>
double doubleNumber = 12.2345912375;
int accurracy = 10;
wxString numberString = wxNumberFormatter::ToString(doubleNumber, accurracy);
How to convert a wxString to a floating point number?
wxString number(wxT("3.14159"));
double value;
if(!number.ToDouble(&value)){ /* error! */ }
so the string number is written to value.
I hope this is helpfull to someone, as everytime I wanted to convert something I started searching the web again. If there are improvements to make or I forgot something, feel free to correct me, as this is my first Q&A :)
All these questions and many more are answered in the wxWidgets wiki
https://wiki.wxwidgets.org/Converting_everything_to_and_from_wxString

How can I insert integer into a string using insert function in C++?

Below check is string and temp1->data is integer. I want to insert temp1->data into check. So I type cast int into const char*. This gives warning : cast to pointer from integer of different size [-Wint-to-pointer-cast]
Part of code:
temp1 = head;
std::string check;
check = "";
int i = 0;
while(temp1 != NULL)
{
check.insert(i, (const char*)temp1->data);// here is the warning
temp1 = temp1->next;
++i;
}
I want to know what other choices I have to insert the integer (temp1->data) into string(check) using insert function and what is the actual effect of warning [-Wint-to-pointer-cast] on my code.
Points:
data is integer, next is pointer to Node
I'm trying to implement a function to check if a linked list containing single digit number is palindrome or not. Yes, I know other methods for this but I just want to implement through this method too.
Here I want to store all the data of linked list into a string and directly check if the string is palindrome or not.
This question may seem duplicate of this . But it is not, here I explicitly asked for inserting integer into string using insert function contained in string class.
PS: on using std::to_string(temp1->data) gives me error ‘to_string’ is not a member of ‘std’.
You can use std::to_string function to convert integer to string and then insert it in a string using insert function on std::string.
std::string check;
check = "";
int i = 0;
check.insert(i, std::to_string(10));
The reason you are getting error "to_string is not a member of std" is may be because you did not include <string> header.
First, here's a way to convert an integer to a string without much work. You basically create a stream, flush the int into it, and then extract the value you need. The underlying code will handle the dirty work.
Here's a quick example:
stringstream temp_stream;
int int_to_convert = 5;
temp_stream << int_to_convert;
string int_as_string(temp_stream.str());
Here's more info on this solution and alternatives if you want to know more:
Easiest way to convert int to string in C++
Regarding the impact of the cast that you're doing, the behavior will be undefined because you're setting char* to an int value. The effect won't be converting the int value to a series of characters, instead you'll be setting the memory location of what the system interprets as the location of first character of a char array to the value of the int.

Exponential Numbers conversion in C++, MFC

I am very new to MFC and now I want to convert Exponential Numbers "4.246E+3" into 4246.
Input is in string and output I want to get it in int.
Please let me know if we have any way(API) to get it in MFC, C++.
Thanks
MAP
Following code will work fine to solve your problem...
#include<sstream>
string str = "4.246e+3";
stringstream ss;
double number;
ss<<str;
ss>>number;
You can the standard library function which allows for str to be in scientific notation.
int stoi (const string& str, size_t* idx = 0, int base = 10);
If you supply idx and it comes back nullptr then str was a pure number, if not then it returns the address of the first invalid character in str.
It's better to use the standard C++ library functions rather than MFC whenever possible to assist in any future porting out of MFC.

Converting a string to double using c_str() in C++

Is it not reccomended to convert a string in such way:
string input = "81.312";
double val = atof(input.c_str());
DO NOT use std::atof in C++. That doesn't check for input error.
Use std::stod. That checks for error also and throws exception accordingly.
Also, it takes std::string const & as argument. So you don't have to pass input.c_str(). Just do this:
double value = std::stod(input);
It is not wrong, but more right would be to use boost::lexical_cast.
You should also check if these tools handle NANs and INFs correctly.

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?