This question already has answers here:
Concatenating strings doesn't work as expected [closed]
(4 answers)
Closed 6 years ago.
I want to create string "hello1world by this two strings:
string s1 = "hello"
string s2 = "world"
I do this:
string my_str;
sprintf(my_str, "%s1%s", s1, s2);
But I have an error:
error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘char*’ for argument ‘1’ to ‘int sprintf(char*, const char*, ...)’
sprintf(my_str, "%s1%s", s1, s2);
How to do it properly?
Please don't use sprintf. It only supports char[] strings, i.e. C strings. So that's why it doesn't compile when you pass std::string.
With std::string, a simple + is all you need:
string my_str = s1 + s2;
If you want to concatenate the two strings, you can use + operator of std::string
string s1 = "hello";
string s2 = "world";
string my_str = s1 + "1" + s2;
For case of two strings formatting use operator+=:
std::string myStr(s1 + "1" + s2);
If you need to do formatting of many strings, a more efficient way will be:
std::string myStr;
myStr.reserve(1048576); // Reserve space in buffer to prevent reallocation
while (<many iterations>)
{
myStr.append(s1);
myStr.append("1");
// Do more formatting here
myStr.append(s2);
}
If you have some non-string values to include in your result you can use std::stringstream from <sstream> header:
std::stringstream ss;
ss << "hello";
ss << 1;
ss << "world";
std::string myStr(ss.str());
I need to mention (thanks #IInspectable for hint) std::stringstream is pretty slow. C++11 offers better way for numbers formatting with use of std::to_string.
std::string s3 = s1 + "1" + s2;
you have many things to do you can use operator +
string a = "hello";
string b = "world";
string ans = a + "1" + b;
you can use string::append
string a = "hello";
string b = "world";
string ans = "";
ans.append(a);
ans.append("1");
ans.append(b);
you can use insert but not pereferd in concate better use + operator or append
string a = "hello";
string b = "world";
a.insert(a.size(),1,'1');
a.insert(a.size(),b);
insert with a string use it as string::insert(index,string);
with characters use it as string::insert(index,len,char);
Related
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str = "Hello";
string s = str[0] + str[1];
cout << s;
return 0;
}
Why does this code gives an error, even if we can concatenate strings?
the reason this fails
std::string s = str[0] + str[1];
is because str[0] and str[1] return a char (H and e):
std::string s = 'H' + 'e';
and adding two chars will not concatenate them, instead their values will be added together. Every character has an assigned number (look up ASCII table)
std::string s = 72 + 101;
and this will fail, as assigning the number 173 to a string doesn't really make sense to the compiler.
there are multiple ways to concatenate variables together, in this case the most simple solution would be
std::string s { str[0], str[1] };
This will be limited to chars though, so you couldn't say { str[0], str[1], 500 }. Therefore the general way to concatenate any number of data, is to use std::ostringstream, found in the header <sstream>. This how it is used:
std::ostringstream stream;
stream << str[0] << str[1] << 500;
std::string s = stream.str();
Read here why using namespace std; is considered bad practice and here why <bits/stdc++.h> is to be avoided.
str[0] and str[1] are giving you characters, not strings. Adding them gives you another character, which cannot be casted to a string.
You can construct a new string with a substring of the first part of the string you want to concatenate, and then insert the substring of the second part of the string you want to concatenate, like so:
// Construct new string that contains the first character of str
string s(str.begin(), str.begin() + 1);
// Add the second character of str onto the end of s
s.insert(s.end(), str.begin() + 1, str.begin() + 2);
My problem is that I get an error when trying to add hard-coded text, "334 " before my decoded user input:
received = buf;
if(strncmp(buf, "334 ", 4) == 0){
decoding(received.c_str() + 4, strlen(buf + 4), buf);
received = "334 " + buf;
}
Here is the error I get:
invalid operands of types 'const char[5] and 'char[300] to binary 'operator+'
std::string has a constructor that takes a char *, so you can create a std::string from buf like this:
std::string buf_str(buf);
From cplusplus.com's list of std::string constructors:
string (const char* s);
Copies the null-terminated character sequence (C-string) pointed by s.
I dunno if that can suit you but you can consider using the stringstream class so that you can merge the text variables as:
stringstream longone;
string text;
longone << received << "334 ";
string=longone.str()
I was wondering how I could convert an int to a string and then add it to an existin string. i.e.
std::string s = "Hello";
//convert 1 to string here
//add the string 1 to s
I hope I'm making sense. Thank you very much in advance for any answer.
If the number you want to append is an integer or floating point variable, then use std::to_string and simply "add" it:
int some_number = 123;
std::string some_string = "foo";
some_string += std::to_string(some_number);
std::cout << some_string << '\n';
Should output
foo123
The "modern" way is to use std::to_string(1). In fact, various overloads of std::to_string exist for different number types.
Putting this together you can write std::string s = "Hello" + std::to_string(1);
Alternatively you can use std::stringstream which can be faster due to fewer string concatenation operations which can be expensive:
std::stringstream s;
s << "Hello" << 1;
// s.str() extracts the string
This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 8 years ago.
Here str2 is a string I need to append and str1 is the string I append onto str2. After I append last to str2 I need to append a number (int cnt) to str2. So I am using the below code, which came to my mind and it is working. Is it wrong to code like this, since I saw the usage of string s = lexical_cast<string>(a); and itoa (i,buffer,10); implementations where compiler complaints about the library.
string str2;
string str1;
int cnt;
str2 += str1 ;
str2 += char(cnt+48);//cnt converted to ASCII char and appended;
This statement
str2 += char(cnt+48);
is bad. Firstly it uses magic number 48. It would be better to write at least as
str2 += char( cnt + '0' );
Secondly the code will work only if cnt contains a number with one digit.
It would be better to use standard function std::to_string For example
str2 += std::to_string( cnt );
If you don't want to use c++11 and its std::to_string(...) you can use ostringstream class.
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
ostringstream ss;
ss << 1;
string str = ss.str();
cout << str << endl;
return 0;
}
Output:
1
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am new to c++ and am looking for a way to concatenate three char* strings together ? Can anyone show me some sample code ?
Kind Regards,
In C++ you typically use std::string for strings. With that you can concatenate with the + operator. For instance:
std::string s = s1 + s2 + s3;
where s1, s2 and s3 are your three strings held in std::string variables.
If you have s1, s2 and s3 as char* or const char* then you write it a little differently.
std::string s = s1; // calls const char* constructor
s += s2; // calls operator+=() overload that accepts const char*
s += s3; // and again
If you really want to use null-terminated C strings, and C string functions, then you use strcpy to copy and strcat to concatenate.
char[SOME_LARGE_ENOUGH_VALUE] str;
strcpy(str, s1);
strcat(str, s2);
strcat(str, s3);
where s1, s2 and s3 are your three strings as char* or const char*.
Of course, choosing SOME_LARGE_ENOUGH_VALUE is the fun part. If this is a learning exercise, then you might like to learn how to allocate the string dynamically.
char *str = new char[strlen(s1) + strlen(s2) + strlen(s3) + 1];
Then you can use the strcpy, strcat shuffle above. But now you are responsible for destroying the raw memory that you allocated. So, think about how to do that in a robust way, and then use std::string!
From the comments, it seems you want to concatenate three strings, and then pass the resulting string to a low-level hash function that accepts a C string. So, I suggest that you do all your work with std::string. Only at the last minute, when you call the hash function, use the c_str() function to get a const char* representation of the concatenated string.
const char * foo = "foo";
const char * bar = "bar";
const char * baz = "baz";
One option:
std::string s = foo;
s += bar;
s += baz;
Another option:
std::stringstream ss;
ss << foo << bar << baz;
std::string s = ss.str();
Another option of last resort:
char* s = new char [strlen (foo) + strlen (bar) + strlen (baz) + 1];
s[0] = 0;
strcat (s, foo);
strcat (s, bar);
strcat (s, baz);
// ...
delete [] s;
std::string s1( "Hello " );
std::string s2( "C++ " );
std::string s3( "amateur" );
s1 += s2 + s3;
std::cout << s1 << std::endl;
Or
char s1[18] = "Hello ";
char s2[] = "C++ ";
char s3[] = "amateur";
std::strcat( std::strcat( s1, s2 ), s3 );
std::cout << s1 << std::endl;
A simple way to concatenate:
#include <iostream>
int main()
{
const char* a = "welcome ";
const char* b = "to C++ ";
const char* c = "world";
std::string d(a);
std::cout<< d.append(b).append(c);
return 0;
}