Failing to convert a string to int in c++ - c++

I started learning C++ few days abck and I have been working on a sample project where I need to convert a string to int. I am facing an issue in the following code:
#include <string>
#include <stdlib.h>
string sIMX = "45250";
int IMXValue = atoi(sIMX);
int IMXDeg = IMXValue/10;
string sIMXFinal = std::to_string(IMXDeg);
strcpy(sIMX, sIMXFinal);
cout<<"String Value = "<<sIMX;
I have to convert a value present in string to an integer... divide it by 10 and then store the value in a string and display it.
Error: 'to_string' is not a member of 'std'

So I think you are hopefully using c++11 in which case you should do this:
#include <string>
using namespace std;
string sIMX = "45250";
int IMXValue = stoi(sIMX);
int IMXDeg = IMXValue/10;
string sIMXFinal = to_string(IMXDeg);
cout << "String Value = " <<sIMXFinal;
and if you wanted to be clever:
string sIMX = "45250";
string sIMXFinal = to_string(stoi(sIMX)/10);
this is all c++ stuff and should make your life a little easier. You could also use stringstreams. Dont forget to compile with:
g++ -std=c++11 yourprogram.cpp -o outputname

Your approach is quizzical as the recommended way of converting strings to integers is using a stringstream
std::string number = "123456789";
std::stringstream ss(number);
int num = 0;
ss >> num;
if (ss.fail()) {
// Error
}
else {
std::cout << "The integer value is: " << num;
}
Requires: <sstream>

Since you are using atoi already, you could use itoa to convert in the opposite direction.

Related

How can i store hex value in string and get the value and size of the string

I am trying to store a hex value in a string and latter retrieve it after some time, but while retrieving No value is coming size of the string is also coming 0. Sample code:
using namespace std;
int main() {
std::string s;
s.assign("\x00\x53"); // std::string s ="\x00\x53"
cout<<s.size();
}
output is coming 0
Try using \\ instead of \:
s.assign("\\x00\\x53");
Now you have:
#include <iostream>
using namespace std;
int main() {
std::string s;
s.assign("\\x00\\x53"); // std::string s ="\x00\x53"
cout << s.size() << endl;
cout << s << endl;
}
Output:
8
\x00\x53
From C++14 onwards, we have the option of using string literals, using that feature you can do this:
std::string s1 = "\x00\x53"s;
This will do what you expect and will return the correct value for size().
If you cannot use C++14 features, you need to use a string constructor that will allow you to specify the length of the string. You can do this:
std::string s1( "\x00\x53", 2);
You can see demo for both versions here.

Including value of int variable inside of string

I am trying to print the date that the user enters in a program I am working on. In this very simplified example, I am trying to get the value of an int variable inside of a string variable. Here, you can see I have tried static_cast<char>(int).
I have also tried
myStr = num;
myStr = num + 0;
myStr = num + '0';
as well as many other things that do not make sense just to see what the compiler does and what the program does - if I can get it to run.
Here's the few lines I have in this shortened example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 100;
string myStr = static_cast<char>(num);
cout << myStr;
return 0;
}
In my other program, I am trying to insert the year 2017 (saved as an int variable) into a string that contains the rest of the date. I'm just having problems with numbers bigger than 9.
Thanks for any help.
Use the standard library function std::to_string to convert your number to string form.
stringstream ss;
ss << num;
cout << ss.str();
Don't forget to include sstream
As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library and you could use to_string method.
You can use to_string to convert int to String.
#include<String>
std::string int_string = std::to_string(num);
If you have older version of c++,this will work by compiling with the flag -stdc++=11 or higher e.g
g++ filename.cpp -stdc++=11

How to do a true strtoul? Wont intake an actual string

Having an issue inputting an ACTUAL string to strtuol. The input string SHOULD be an unsigned binary value of 32 bits long.
Obviously, there is in issue with InputString = apple; but I'm not sure how to resolve the issue. any thoughts? This shouldnt be that difficult. not sure why I'm having such a hard time with it.
Thanks guys.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
char InputString[40];
char *pEnd = NULL; // Required for strtol()
string apple = "11111111110000000000101010101000";
//cout << "Number? ";
//cin >> InputString;
InputString = apple;
unsigned long x = strtoul(InputString, &pEnd, 2); // String to long
cout << hex << x << endl;
return 1;
}
A better approach would be to avoid the legacy-C functions and use the C++ standard functions:
string apple = "11111111110000000000101010101000";
unsigned long long x = std::stoull(apple, NULL, 2); // defined in <string>
NOTE: std::stoull will actually call ::strtoull internally, but it allows you to just deal with the std::string object instead of having to convert it to a C-style string.
Include :
#include<cstdlib> // for strtol()
#include<cstring> // for strncpy()
and then
strncpy(InputString ,apple.c_str(),40);
^
|
convert to C ctring
Or simply,
unsigned long x = strtoul(apple.c_str(), &pEnd, 2);

String as a parameter (C++)

Is this example code valid?
std::string x ="There are";
int butterflies = 5;
//the following function expects a string passed as a parameter
number(x + butterflies + "butterflies");
The main question here is whether I could just pass my integer as part of the string using the + operator. But if there are any other errors there please let me know :)
C++ doesn't do automatic conversion to strings like that. You need to create a stringstream or use something like boost lexical cast.
You can use stringstream for this purpose like that:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream st;
string str;
st << 1 << " " << 2 << " " << "And this is string" << endl;
str = st.str();
cout << str;
return 0;
}
A safe way to convert your integers to strings would be an excerpt as follows:
#include <string>
#include <sstream>
std::string intToString(int x)
{
std::string ret;
std::stringstream ss;
ss << x;
ss >> ret;
return ret;
}
Your current example will not work for reasons mentioned above.
No, it wouldn't work. C++ it no a typeless language. So it can't automatically cast integer to string. Use something like strtol, stringstream, etc.
More C than C++, but sprintf (which is like printf, but puts the result in a string) would be useful here.

C++ string to double conversion

Usually when I write anything in C++ and I need to convert a char into an int I simply make a new int equal to the char.
I used the code(snippet)
string word;
openfile >> word;
double lol=word;
I receive the error that
Code1.cpp cannot convert `std::string' to `double' in initialization
What does the error mean exactly? The first word is the number 50. Thanks :)
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.
With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)
#include <stdlib.h>
int main()
{
string word;
openfile >> word;
double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
previously (the function requires it)*/
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999 (which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string, it's a string, and if something is declared as a double, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!" to a double, there's no meaningful conversion. Sure, you could just set the double to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail() method to return true. For example:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
If you are reading from a file then you should hear the advice given and just put it into a double.
On the other hand, if you do have, say, a string you could use boost's lexical_cast.
Here is a (very simple) example:
int Foo(std::string anInt)
{
return lexical_cast<int>(anInt);
}
The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.
Compile and run this program, then study it. It is simple
#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;
int main()
{
// Converting the content of a char array or a string to a double variable
double d;
string S;
S = "4.5";
istringstream(S) >> d;
cout << "\nThe value of the double variable d is " << d << endl;
istringstream("9.87654") >> d;
cout << "\nNow the value of the double variable d is " << d << endl;
// Converting a double to string with formatting restrictions
double D=3.771234567;
ostringstream Q;
Q.fill('#');
Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
S = Q.str(); // formatted converted double is now in string
cout << "\nThe value of the string variable S is " << S << endl;
return 0;
}
Prof. Martinez
Coversion from string to double can be achieved by
using the 'strtod()' function from the library 'stdlib.h'
#include <iostream>
#include <stdlib.h>
int main ()
{
std::string data="20.9";
double value = strtod(data.c_str(), NULL);
std::cout<<value<<'\n';
return 0;
}
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}
or
//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]- (s[x]<='9' ? '0':'0'+7) ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}