Reputation: 37
everybody I have problem with string concatenation in C++, here is my code
map<double, string> fracs;
for(int d=1; d<=N; d++)
for(int n=0; n<=d; n++)
if(gcd(n, d)==1){
string s = n+"/"+d;// this does not work in C++ but works in Java
fracs.insert(make_pair((double)(n/d), s));
}
How can I fix my code?
Upvotes: 1
Views: 2146
Reputation: 3
I think sprintf(), which is a function used to send formatted data to strings, would be a much clearer way to do it. Just the way you would use printf, but with the c-style string type char* as a first(additional) argument:
char* temp;
sprint(temp, "%d/%d", n, d);
std::string g(temp);
You could check it out at http://www.cplusplus.com/reference/cstdio/sprintf/
Upvotes: 0
Reputation: 39109
Use streams, in your case, a stringstream:
#include <sstream>
...
std::stringstream ss;
ss << n << '/' << d;
Later, when done with your work, you can store it as an ordinary string:
const std::string s = ss.str();
Important (side-) note: Never do
const char *s = ss.str().c_str();
stringstream::str()
produces a temporary std::string
, and according to the standard, temporaries live until the end of the expression. Then, std::string::c_str()
gives you a pointer to a null-terminated string, but according to The Holy Law, that C-style-string becomes invalid once the std::string
(from which you receved it) changes.
It might work this time, and next time, and even on QA, but explodes right in the face of your most valuable customer.
The std::string
must survive until the battle is over:
const std::string s = ss.str(); // must exist as long as sz is being used
const char *sz = s.c_str();
Upvotes: 2
Reputation: 76143
In C++ you have to convert an int
to a string
before you can concatenate it with another string
using the + operator.
See Easiest way to convert int to string in C++.
Upvotes: 2
Reputation: 31597
Unlike in Java, in C++ there is no operator+
that explicitly converts a number to a string. What is usually done in C++ in cases like this is...
#include <sstream>
stringstream ss;
ss << n << '/' << d; // Just like you'd do with cout
string s = ss.str(); // Convert the stringstream to a string
Upvotes: 0
Reputation: 55816
No one has suggested it yet but you can also take a look at boost::lexical_cast<>
.
While this method is sometimes criticized because of performance issues, it might be ok in your situation, and it surely makes the code more readable.
Upvotes: 0
Reputation: 3155
You could use a stringstream.
stringstream s;
s << n << "/" << d;
fracs.insert(make_pair((double)n/d, s.str()));
Upvotes: 0
Reputation: 93090
n
and d
are integers. Here is how you can convert integer to string:
std::string s;
std::stringstream out;
out << n << "/" << d;
s = out.str();
Upvotes: 0
Reputation: 63708
Try like this.
stringstream os;
os << n << "/" << d;
string s =os.str();
Upvotes: 2