This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 2 years ago.
Please tell me how to convert int to char in c++ style? The content in str1 is "\001", while the content in str2 is "1"; Can I use static_cast to get the same result as str2?
The code is as follows:
#include <iostream>
using namespace std;
int main()
{
int a = 1;
string str1;
string str2;
str1.push_back(static_cast<char>(a));
str2.push_back('0' + a);
cout << str1 << str2;
return 0;
}
It depends on the exact use-case. For a direct int-to-string conversion, use std::to_string.
When streaming the output, there are usually better options, including using fmt (part of C++20, available as a separate library before that).
Related
This question already has answers here:
C++: Converting a double/float to string, preserve scientific notation and precision
(2 answers)
Closed 5 years ago.
This question is very clearly in no way an "exact duplicate" of the marked question, and that post does not address my goal.
If I have:
double yuge = 1e16;
And I try to add it to a string like this:
std::string boogers = std::to_string (yuge) + ".csv";
I get a file name of 100000000000000000.csv.
I want a nice compact version like 1e16.csv.
As you can see, I would like to use it as a file name, so output methods arent helpful. Halp! Thanks.
you can use std::stringstream to construct the string instead of + operator.
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
int main()
{
double youge = 1e16;
std::stringstream ss;
ss<<youge<<".csv";
std::string filename = ss.str(); // filename = 1e+16.csv
filename.erase(std::remove(filename.begin(), filename.end(), '+'), filename.end());// removing the '+' sign
std::cout<<filename; // 1e16.csv
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I need a c-string format of toString(), but how do I convert it? Here is the function:
string toString(){
string tmp;
char buf[80];
if (*d != 1)
sprintf_s(buf, "%d/%d", *n, *d);
else sprintf_s(buf, "%d", *n);
tmp = string(buf);
return tmp;
}
need a c-string format of toString()
If you just need to convert the output of toString(), you can use
const char* s = toString().c_str();
Your function currently is returning a string (I'm guessing your code has using namespace std) which means a C++ string object.
If you don't absolutely need C strings, I would recommend using C++ strings, since they are more current and just easier to work with. However, if for reasons somewhere else in the code you do need a C string, your function should look like
char* toString() {
// formatting your output
}
Because all a C string is is a null terminated ('\0') array of char, and an array is equivalent to a pointer to the first element, so that's where char* comes from.
In either case, C++ stringstreams will make formatting your output far more intuitive. You will need #include <sstream> and then some googling will steer you in the right direction. This solution also works if you need a C string, because C++ strings have a method called c_str() that converts C++ strings into C strings (null terminated array of characters):
#include <string>
#include <sstream>
using namespace std;
char* toString() {
stringstream ss; // these are so useful!
if (*d != 1) {
// this probably isn't the exact formatting you are looking for,
// but stringstreams can certainly do it if you research a bit!
ss << *n << *d;
}
else {
ss << *n;
}
string output = ss.str();
return output.c_str();
}
This question already has answers here:
convert string to integer in c++
(3 answers)
Closed 8 years ago.
I'm new to CPP.
I'm trying to create small console app.
my qustion is, is there a way to change char array to integer...?!
for example:
char myArray[]= "12345678" to int = 12345678 ...?!
tnx
You don't "change" a type. What you want is to create an object of a certain type, using an object of the other type as input.
Since you are new to C++, you should know that using arrays for strings is not recommended. Use a real string:
std::string myString = "12345678";
Then you have two standard ways to convert the string, depending on which version of C++ you are using. For "old" C++, std::istringstream:
std::istringstream converter(myString);
int number = 0;
converter >> number;
if (!converter) {
// an error occurred, for example when the string was something like "abc" and
// could thus not be interpreted as a number
}
In "new" C++ (C++11), you can use std::stoi.
int number = std::stoi(myString);
With error handling:
try {
int number = std::stoi(myString);
} catch (std::exception const &exc) {
// an error occurred, for example when the string was something like "abc" and
// could thus not be interpreted as a number
}
Use boost::lexical_cast:
#include <boost/lexical_cast.hpp>
char myArray[] = "12345678";
auto myInteger = boost::lexical_cast<int>(myArray);
The atoi function does exactly this.
Apart from atoi() with C++11 standard compliant compiler you can use std::stoi().
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I tokenize a string in C++?
hello every one i want to divide my string into two parts based on '\t' is there any built in function i tried strtok but it take char * as first in put but my variable is of type string
thanks
#include <sstream>
#include <vector>
#include <string>
int main() {
std::string str("abc\tdef");
char split_char = '\t';
std::istringstream split(str);
std::vector<std::string> token;
for(std::string each; std::getline(split, each, split_char); token.push_back(each));
}
Why can't you use C standard library?
Variant 1.
Use std::string::c_str() function to convert a std::string to a C-string (char *)
Variant 2.
Use std::string::find(char, size_t) to find a necessary symbol ('\t' in your case) than make a new string with std::string::substr. Loop saving a 'current position' till the end of line.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to parse a string to an int in C++?
How do you convert a C++ string to an int?
Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).
Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.
#include <sstream>
// st is input string
int result;
stringstream(st) >> result;
Use the C++ streams.
std::string plop("123");
std::stringstream str(plop);
int x;
str >> x;
/* Lets not forget to error checking */
if (!str)
{
// The conversion failed.
// Need to do something here.
// Maybe throw an exception
}
PS. This basic principle is how the boost library lexical_cast<> works.
My favorite method is the boost lexical_cast<>
#include <boost/lexical_cast.hpp>
int x = boost::lexical_cast<int>("123");
It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and << operators).
I have used something like the following in C++ code before:
#include <sstream>
int main()
{
char* str = "1234";
std::stringstream s_str( str );
int i;
s_str >> i;
}
C++ FAQ Lite
[39.2] How do I convert a std::string to a number?
https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num
Let me add my vote for boost::lexical_cast
#include <boost/lexical_cast.hpp>
int val = boost::lexical_cast<int>(strval) ;
It throws bad_lexical_cast on error.
Use atoi
Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.
Am I just missing the point here?
in "stdapi.h"
StrToInt
This function tells you the result, and how many characters participated in the conversion.