Convert a Long in a String C++? [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ long to string
Easiest way to convert int to string in C++
I am use to Java where I could just use .toString() on almost anything but I am trying a few problems in C++
I can not figure out how to make a long value into a string.

You can either use a string stream:
#include <sstream>
#include <string>
long x;
// ...
std::ostringstream ss;
ss << x;
std::string result = ss.str();
Or you can use Boost's lexical_cast:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(x);
I think it's a common opinion that this aspect of the language isn't quite as elegant as it could be.
In the new C++11, things are a bit easier, and you can use the std::to_string() function:
#include <string>
std::string s = std::to_string(x);

#include <string>
#include <sstream>
std::ostringstream ss;
long i = 10;
ss << i;
std::string str = ss.str();

You can use a stringstream.
std::ostringstream ss;
ss << aLongNumber;
ss.str()
You use operator << like iostream cout and cin. And you use str() method to get the string.

Related

Convert large double to scientific notation for use as string? [duplicate]

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
}

How do I concatenate a vector of strings in c++ with boost?

I have a vector of strings, like this:
{"abc"}{"def"}{"ghi"}
I want to concatenate them into a single string, with a separator like "-".
Is there a concise (pretty) way of doing this without using a typical for loop? I have c++03 and boost available to me.
Sure, boost provides a convenient algorithm for achieving what you are trying to do. In higher level languages you may have spotted a join function. Boost provides an equivalent algorithm in the join function.
#include <boost/algorithm/string/join.hpp>
using namespace std;
string data[] = {"abc","def","ghi"};
const size_t data_size = sizeof(data) / sizeof(data[0]);
vector<string> stringVector(data, data + data_size);
string joinedString = boost::algorithm::join(stringVector, "-");
Just for reference, there is currently a proposal for std::join, which you can check out here.
But since you have boost available, you can use boost::algorithm::join, which takes a sequence of strings and a separator, like so:
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/join.hpp>
int main() {
std::vector<std::string> words;
words.push_back("abc");
words.push_back("def");
words.push_back("ghi");
std::string result = boost::algorithm::join(words, "-");
std::cout << result << std::endl;
}
Prints:
abc-def-ghi
Another option using only the STL is:
std::ostringstream result;
if (my_vector.size()) {
std::copy(my_vector.begin(), my_vector.end()-1,
std::ostream_iterator<string>(result, "-"));
result << my_vector.back();
}
return result.str()

How can I initialize a *char using user input?

Initializing a string in C# is as easy as this:
string str = Console.Read();
with this method, I don't need to know the size of the string which the user enters. But I cannot find a way like this in C++. I want my string to be defined as char *input, and I don't want to know the size of the string.
How can I achieve what I want?
Why not use C++'s string type?
#include <iostream>
#include <string>
int main() {
std::string foo;
std::cin >> foo;
std::cout << foo << "\n";
}
C++ has a string class which works much like C#'s string. So use it. :)
char* is not a string. It's just the closest you get if you're working in C.
So, #include <string>, and then use std::string instead of char*.
Use std::string and std::cin:
std::string str;
std::cin >> str;

How to convert a string to complex<float> in C++?

How do I easily convert a string containing two floats separated by a comma into a complex?
For instance:
string s = "123,5.3";//input
complex<float> c(123,5.3);//output/what I need
Is there an simpler/faster way than to split the string, read the two values and return thecomplex<float>?
Just add the parentheses and the default operator>> will do it for you:
#include <iostream>
#include <string>
#include <complex>
#include <sstream>
int main()
{
std::string s = "123,5.3";//input
std::istringstream is('(' + s + ')');
std::complex<float> c;
is >> c;
std::cout << "the number is " << c << "\n";
}
PS. Funny how everyone's style is slightly different, although the answers are the same.
If you are ready to handle exceptions, this can be done with boost, too:
std::complex<float> c = boost::lexical_cast<std::complex<float> >('('+s+')');
The complex class has an extraction operator. You could add parentheses around the string, and then the class would read in the number for you.

How do you convert a C++ string to an int? [duplicate]

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.