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
Related
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.
I have an input file which I'm reading in with the basic myFile >> variable since I know the format and the format will always be correct. The file I'm reading in is formatted as instruction <num> <num> and to make >> work, I'm reading everything in as a string. If I have 3 variables, one to take in each piece of the line, how can I then turn string <1> (for example) into int 1? I know the string's first and last characters are brackets which need to be removed, then I could cast to an int, but I'm new to C++ and would like some insight on the best method of doing this (finding and removing the <>, then casting to int)
use stringstream
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string str = "<1>";
int value;
std::stringstream ss(str);
char c;
ss >> c >> value >> c;
std::cout << value;
}
First to get the middle character out you can just do char myChar = inputString.at(1);. Then you can do int myInt = (int)myChar;
Even if you remove the <> characters, your still importing the file content into a string using >> so you still need to cast it to an int. If you have only 1 value, you can follow what Nicholas Callahan wrote in the previous answer, but if you have multiple characters you want to read as int, you dont have a choice but to cast.
You can also resort to sscanf.
#include <cstdio>
#include <iostream>
#include <string>
int main()
{
std::string str = "<1234>";
int value;
sscanf(str.c_str(), "<%d>", &value);
std::cout << value << std::endl;
}
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.
This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 9 years ago.
Coming from a C# background, In C# I could write this:
int int1 = 0;
double double1 = 0;
float float1 = 0;
string str = "words" + int1 + double1 + float1;
..and the casting to strings is implicit. In C++ I understand the casting has to be explicit, and I was wondering how the problem was usually tackled by a C++ programmer?
There's plenty of info on the net already I know, but there seems to quite a number of ways to do it and I was wondering if there wasn't a standard practice in place?
If you were to write that above code in C++, how would you do it?
Strings in C++ are just containers of bytes, really, so we must rely on additional functionality to do this for us.
In the olden days of C++03, we'd typically use I/O streams' built-in lexical conversion facility (via formatted input):
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::stringstream ss;
ss << "words" << int1 << double1 << float1;
std::string str = ss.str();
You can use various I/O manipulators to fine-tune the result, much as you would in a sprintf format string (which is still valid, and still seen in some C++ code).
There are other ways, that convert each argument on its own then rely on concatenating all the resulting strings. boost::lexical_cast provides this, as does C++11's to_string:
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::string str = "words"
+ std::to_string(int1)
+ std::to_string(double1)
+ std::to_string(float1);
This latter approach doesn't give you any control over how the data is represented, though (demo).
std::stringstream
std::to_string
If you can use Boost.LexicalCast (available for C++98 even), then it's pretty straightforward:
#include <boost/lexical_cast.hpp>
#include <iostream>
int main( int argc, char * argv[] )
{
int int1 = 0;
double double1 = 0;
float float1 = 0;
std::string str = "words"
+ boost::lexical_cast<std::string>(int1)
+ boost::lexical_cast<std::string>(double1)
+ boost::lexical_cast<std::string>(float1)
;
std::cout << str;
}
Live Example.
Note that as of C++11, you can also use std::to_string as mentioned by #LigthnessRacesinOrbit.
Being a C developer, I would use the C string functions, as they are perfectly valid in C++, and let you be VERY explicit with respect to the formatting of numbers (ie: integers, floating point, etc).
http://www.cplusplus.com/reference/cstdio/printf/
In the case of this, sprintf() or snprintf() is what you are looking for. The formats specifiers make it very obvious in the source code itself what your intent was as well.
The best way to cast numbers into std::string in C++ is to use what is already available.
The library sstream provide a stream implementation for std::string.
It is like using a stream ( cout, cin ) for example
Its easy to use :
http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream
#include <sstream>
using std::stringstream;
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::endl;
int main(){
stringstream ss;
string str;
int i = 10;
ss << i;
ss >> str;
cout << str << endl;
}
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.