473,795 Members | 2,974 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

joining 2 strings

Hi,
I tried to use the java approach to join 2 strings

int w=0;
string z="blah " + w + "blah "
but this gives me an error

but this works
string z("blah");
z+=w;
z+="blah";

Is there a better way of writing this?

Cheers,
Sam
Aug 31 '08 #1
7 1995
cch
于 Sat, 30 Aug 2008 21:01:48 -0700,sam.bark er0写到:
Hi,
I tried to use the java approach to join 2 strings

int w=0;
string z="blah " + w + "blah "
but this gives me an error

but this works
string z("blah");
z+=w;
z+="blah";

Is there a better way of writing this?

Cheers,
Sam
I am worry that the w was treated as four chars, not what you want.

The stringstream might help.
Aug 31 '08 #2
sa*********@gma il.com wrote:
Hi,
I tried to use the java approach to join 2 strings

int w=0;
string z="blah " + w + "blah "
but this gives me an error

but this works
string z("blah");
z+=w;
z+="blah";

Is there a better way of writing this?
Repeat after me. C++ is not Java.

Now, your problem. String literals are of type const char *. You can't
add them. Also, what you think the adding of w does is not right.

I assume you're trying to get "blah0blah" . For that you should use a
stringstream.

#include <sstream>
#include <string>

int main()
{
int w = 0;
std::ostreamstr ing ss;
ss << "blah" << w << "blah";
std::string z = ss.str();
}
Aug 31 '08 #3
sa*********@gma il.com wrote:
Hi,
I tried to use the java approach to join 2 strings

int w=0;
string z="blah " + w + "blah "
but this gives me an error

but this works
string z("blah");
z+=w;
z+="blah";
Define works. Have you checked the result?

--
Ian Collins.
Aug 31 '08 #4
On Aug 31, 5:17*am, red floyd <no.spam.h...@e xample.comwrote :
sam.bark...@gma il.com wrote:
Hi,
I tried to use the java approach to join 2 strings
int w=0;
string z="blah " + w + "blah "
but this gives me an error
but this works
string z("blah");
z+=w;
z+="blah";
Is there a better way of writing this?

Repeat after me. *C++ is not Java.

Now, your problem. *String literals are of type const char *. *You can't
add them. *Also, what you think the adding of w does is not right.

I assume you're trying to get "blah0blah" . *For that you should use a
stringstream.

#include <sstream>
#include <string>

int main()
{
* *int w = 0;
* *std::ostreamst ring ss;
* *ss << "blah" << w << "blah";
* *std::string z = ss.str();

}- Hide quoted text -

- Show quoted text -
I am not keen on the insistence that std::ostringstr eam is the only
valid way to convert a variable to its string representation.
ostringstream is very useful for building a sentence out of assorted
variables, but its flexibility does cost in performance. So while I do
use the 'stream solution in UI code and the like, in more performance
sensitive situations I would generally solve the original problem
using code along the lines of:

string z("blah");
char buffer[12];
z += _atol(w, buffer, 10); // convert long to C string
z += "blah";

(Where I think I'm assuming posix conformance? Is _atol more than
likely to be about?)

I would not even try to use operator+ in this situation, as it uses a
temporary to store the return value for each invocation. Whereas
operator+= simply appends the new string to the buffer of the existing
instance. But if you were determined to do it, then the following
"works".

char buffer[12];
string z = string("blah") + _ltoa(w, buffer, 10) + "blah ";

Note that I would generally wrap the _atol and buffer in a naive
little class. This class is only intended to be used with operator+=
and does will not even compile in most other situations.

class ToString
{
public:
ToString(long value)
{
_ltoa(value, buffer, radix);
}

operator const char*() const
{
return buffer;
}

private:
static const int radix = 10;
// INT_MIN (-2147483647 - 1)
// INT_MAX 2147483647
// longest string = 11 chars + 1 for null terminator
static const int bufferSize = 12;
char buffer[bufferSize];
};

Which allows you to write:

string z("blah");
z += ToString(w);
z += "blah";

The boost.lexical_c ast also allows you to write code of a similar form

using boost::lexical_ cast;

string z("blah");
z += lexical_cast<st ring>(w);
z += "blah";

but lexical_cast uses std::ostreamstr eam to do the work so has the
same performance as the normal 'stream solution.

Andy

Aug 31 '08 #5
On 2008-08-31 12:23, an**********@ho tmail.com wrote:
On Aug 31, 5:17 am, red floyd <no.spam.h...@e xample.comwrote :
>sam.bark...@gm ail.com wrote:
Hi,
I tried to use the java approach to join 2 strings
int w=0;
string z="blah " + w + "blah "
but this gives me an error
but this works
string z("blah");
z+=w;
z+="blah";
Is there a better way of writing this?

Repeat after me. C++ is not Java.

Now, your problem. String literals are of type const char *. You can't
add them. Also, what you think the adding of w does is not right.

I assume you're trying to get "blah0blah" . For that you should use a
stringstream .

#include <sstream>
#include <string>

int main()
{
int w = 0;
std::ostreamstr ing ss;
ss << "blah" << w << "blah";
std::string z = ss.str();

}- Hide quoted text -

- Show quoted text -

I am not keen on the insistence that std::ostringstr eam is the only
valid way to convert a variable to its string representation.
ostringstream is very useful for building a sentence out of assorted
variables, but its flexibility does cost in performance. So while I do
use the 'stream solution in UI code and the like, in more performance
sensitive situations I would generally solve the original problem
using code along the lines of:

string z("blah");
char buffer[12];
z += _atol(w, buffer, 10); // convert long to C string
z += "blah";

(Where I think I'm assuming posix conformance? Is _atol more than
likely to be about?)
Not very likely at all, as far as I can see. POSIX only defines atol()
but no _atol(), and I think that holds for most functions beginning with
an underscore (I could only find 5 functions in POSIX beginning with an
underscore).

If you are in need of performance and want to construct strings I think
using snprintf() is probably the best idea, just make sure that the
return-value is less than n.

--
Erik Wikström
Aug 31 '08 #6
Erik Wikström wrote:
On 2008-08-31 12:23, an**********@ho tmail.com wrote:
>On Aug 31, 5:17 am, red floyd <no.spam.h...@e xample.comwrote :
>>sam.bark...@g mail.com wrote:
Hi,
I tried to use the java approach to join 2 strings

int w=0;
string z="blah " + w + "blah "
but this gives me an error

but this works
string z("blah");
z+=w;
z+="blah";

Is there a better way of writing this?

Repeat after me. C++ is not Java.

Now, your problem. String literals are of type const char *. You can't
add them. Also, what you think the adding of w does is not right.

I assume you're trying to get "blah0blah" . For that you should use a
stringstrea m.

#include <sstream>
#include <string>

int main()
{
int w = 0;
std::ostreamstr ing ss;
ss << "blah" << w << "blah";
std::string z = ss.str();

}- Hide quoted text -

- Show quoted text -

I am not keen on the insistence that std::ostringstr eam is the only
valid way to convert a variable to its string representation.
ostringstrea m is very useful for building a sentence out of assorted
variables, but its flexibility does cost in performance. So while I do
use the 'stream solution in UI code and the like, in more performance
sensitive situations I would generally solve the original problem
using code along the lines of:

string z("blah");
char buffer[12];
z += _atol(w, buffer, 10); // convert long to C string
z += "blah";

(Where I think I'm assuming posix conformance? Is _atol more than
likely to be about?)

Not very likely at all, as far as I can see. POSIX only defines atol()
but no _atol(), and I think that holds for most functions beginning with
an underscore (I could only find 5 functions in POSIX beginning with an
underscore).
I think Andy is thinking of ltoa (convert int to string), which is not
defined by POSIX, AFAIK. The idiomatic (though kind of ugly) POSIX solution
is
char buf[12];
snprintf(buf, sizeof(buf), "%d", i);
or
char buf[200];
snprintf(buf, sizeof(buf), "Blah %dblah", w);
std::string z(buf);
Aug 31 '08 #7
On Aug 31, 10:23*pm, andy_west...@ho tmail.com wrote:
I am not keen on the insistence that std::ostringstr eam is the only
valid way to convert a variable to its string representation.
ostringstream is very useful for building a sentence out of assorted
variables, but its flexibility does cost in performance.
class ToString
{
public:
* * ToString(long value)
* * {
* * * * _ltoa(value, buffer, radix);
* * }

* * operator const char*() const
* * {
* * * * return buffer;
* * }

private:
* * static const int radix = 10;
* * // INT_MIN * * (-2147483647 - 1)
* * // INT_MAX * * 2147483647
* * // longest string = 11 chars + 1 for null terminator
* * static const int bufferSize = 12;
* * char buffer[bufferSize];
};
This seems like a poor idea to me, if your code
is compiled on a system where ints are bigger then
it will silently cause a buffer overflow.

Anyway, I think you will find that stringstream
does something like this internally anyway,
except it doesn't need to allocate as much memory!

(You have to allocate a 'ToString' object, but the
stringstream may already have enough memory allocated
in its internal buffer to convert the int without
having to allocate more memory).
Sep 1 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1557
by: socialism001 | last post by:
I'm new to php and have read the implode statement on php.net but I guess I still don't understand it. Below is what I have: $value = implode($disp_cap," - ",substr($value,0,300)); $disp_cap = Office Space $value = 3,000 sq.ft. located at the intersection of... I need the $value to join the two so I would get Office Space - 3,000 sq.ft. located at the...
1
4989
by: Joe | last post by:
I've got 3 columns in a mysql database that I am trying to join. I'm using CONCAT(), but it's giving me NULL results. This has worked for me before ... What am I doing wrong? Here's a straight select: mysql> select peopleID, firstName, middleInit, lastname -> from people; +----------+-----------+------------+------------+ | peopleID | firstName | middleInit | lastname |
2
3511
by: James | last post by:
Can anyone please shed some light on the following... I have a framework that uses dynamically created tables, named using an incremental "attribute set ID", as follows: attrdata_1 attrdata_2 attrdata_3 etc, etc...
9
1878
by: Eric Sabine | last post by:
Can someone give me a practical example of why I would join threads? I am assuming that you would typically join a background thread with the UI thread and not a background to a background, but since I'm asking in the first place, assume that assumption to be very assuming. thanks, Eric
10
25546
by: Captain Nemo | last post by:
Hi I'm working on an ASP project where the clients want to be able to effectively perform SELECT queries joining tables from two different databases (located on the same SQL-Server). Does this involve creating virtual tables that link to another database, or am I completely on the wrong track? Any hints as to where I might find more information (buzz-words, etc.) would
2
1550
by: Wally | last post by:
Dim var1 as String Dim var2 as String var1="message1" var2="message2" how do I join the two string variables?
13
1354
by: benoit.lefebvre | last post by:
How can I join args from a function ? Here is what I've done so far but I'm getting weird results code: ------------8<-------------------------- #include<stdio.h> int main (int argc, char *argv) {
2
2266
by: Supermansteel | last post by:
I am joining these 2 tables together in Access 2003 and can't figure out the exact way of writing this script......Can anyone help? I have the following SQL: SELECT PL_Input.Date_ID,Count(PL_Input.+PL_Input.+PL_Input.+PL_Input.+PL_Input.) AS FROM Country INNER JOIN PL_Input ON Country.Country_ID = PL_Input.Country_ID WHERE (((. & "" & . & "" & . & "" & . & "" & .) Like "*2*"))
13
1008
by: SUBHABRATA | last post by:
Dear Group, I am trying the following code line: def try2(n): a1=raw_input("PRINT A STRING:") a2=a1.split() a3="God Godess Heaven Sky" for x in a2: a4=a3.find(x) if a4>-1: a5=a3
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10215
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9043
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7541
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.