Exponential Numbers conversion in C++, MFC - c++

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.

Related

What's the necessity of string in c++ while we already have char[]?

Many topics have discussed the difference between string and char[]. However, they are not clear to me to understand why we need to bring string in c++? Any insight is welcome, thanks!
char[] is C style. It is not object oriented, it forces you as the programmer to deal with implementation details (such as '\0' terminator) and rewrite standard code for handling strings every time over and over.
char[] is just an array of bytes, which can be used to store a string, but it is not a string in any meaningful way.
std::string is a class that properly represents a string and handles all string operations.
It lets you create objects and keep your code fully OOP (if that is what you want).
More importantly, it takes care of memory management for you.
Consider this simple piece of code:
// extract to string
#include <iostream>
#include <string>
main ()
{
std::string name;
std::cout << "Please, enter your name: ";
std::cin >> name;
std::cout << "Hello, " << name << "!\n";
return 0;
}
How would you write the same thing using char[]?
Assume you can not know in advance how long the name would be!
Same goes for string concatenation and other operations.
With real string represented as std::string you combine two strings with a simple += operator. One line.
If you are using char[] however, you need to do the following:
Calculate the size of the combined string + terminator character.
Allocate memory for the new combined string.
Use strncpy to copy first string to new array.
Use strncat to append second string to first string in new array.
Plus, you need to remember not to use the unsafe strcpy and strcat and to free the memory once you are done with the new string.
std::string saves you all that hassle and the many bugs you can introduce while writing it.
As noted by MSalters in a comment, strings can grow. This is, in my opinion, the strongest reason to have them in C++.
For example, the following code has a bug which may cause it to crash, or worse, to appear to work correctly:
char message[] = "Hello";
strcat(message, "World");
The same idea with std::string behaves correctly:
std::string message{"Hello"};
message += "World";
Additional benefits of std::string:
You can send it to functions by value, while char[] can only be sent by reference; this point looks rather insignificant, but it enables powerful code like std::vector<std::string> (a list of strings which you can add to)
std::string stores its length, so any operation which needs the length is more efficient
std::string works similarly to all other C++ containers (vector, etc) so if you are already familiar with containers, std::string is easy to use
std::string has overloaded comparison operators, so it's easy to use with std::map, std::sort, etc.
String class is no more than an amelioration of the char[] variable.
With strings you can achieve the same goals than the use of a char[] variable, but you won't have to matter about little tricks of char[] like pointers, segmentation faults...
This is a more convenient way to build strings, but you don't really see the "undergrounds" of the language, like how to implement concatenation or length functions...
Here is the documentation of the std::string class in C++ : C++ string documentation

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

Tokenizer - Initialization with '{...}' expected for aggregate object

I'm working on creating a program that will take a fraction and reduce it to it's lowest terms. I'm using a tokenizer to parse through the string (In my case I'm reading in a string) and separate the numerator from the denominator.
I'm getting the following error, and am looking for an explanation to why it's happening. I've looked up people with similar problems, but I'm still a beginner looking for a basic explanation and suggestion for an alternative way to solve it.
RationalNum() // Default
:numerator(0), denominator(1){}
RationalNum(int num) // Whole Number
:numerator(num), denominator(1){}
RationalNum(int num, int denom) // Fractional Number
:numerator(num), denominator(denom){}
RationalNum(string s)
{
int num = 0;
char str[] = s;
}
I know the problem lies in the setting the char array to s.
Thanks for taking the time to look at this.
You are trying to initialise an array of char to a std::string, which is an object. The literal meaning of the error is that the compiler is expecting an initialisation that looks something like this :
char str[] = {'1','2','3','4'};
However, since you are planning on string manipulation anyway, you would have a much easier time just keeping the string object rather than trying to assign it to a char array.
Instead of building your parser from scratch, you can use string stream and getline. with '/' as your delimiter. You can initialise an std::stringstream with a string by passing it as an argument when constructing it. You can also use another stringstream to convert a string into a number by using the >> operator.

System::String to ASCII CODE

I'm having issues figuring out how to convert a System::String into its ascii code values. That is, take each character in the string, and create a new string containing each characters integer ascii value.
I know I can marshal a System::String into a std::string, and then do it that way (though I don't know how to do that either, exactly. I'm not up to date on my C++ string operations. My teacher makes us use character arrays...). But there has to be a purely .NET way of achieving this.
I'm very, very new to .NET. This is a homework assignment.
Any help you can give on how to accomplish this would be much appreciated.
Sorry if this is a stupid question =/
Okay I've actually had to do this for homework as well. What I did was using c++ in a .net environment, have a string. This string's characters can be accessed like those of an array, stringname[i...n]. Use a loop of your choice to iterate through all of the positions. To convert each position, all you need to do is:
int asciicode = stringname[i];
stringname[i] = asciicode;
Of course when you then cout the stringname, you will have a bunch of numbers all bunched together so you may not like that, but that's cosmetic things.
This worked for me.
#include <sstream>
std::stringstream convert;
std::string stdString = "whatever the string is";
std::string buffer;
in charBuff;
for(int i = 0; i < stdString.length(); i++)
{
charBuff = (int)stdString.at(i);
convert << charBuff;
}
buffer = convert.str();

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?