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;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a string that I want to encircle with quotes.
What I have so far is this:
#include <stdio.h>
#include <string.h>
int main(){
char my_str[100] = {0};
strcat(my_str, "hello world!");
strcat(my_str, "\"");
strcat(strrev(my_str), "\""); // I want a simpler way for this
strrev(my_str); // and this (though it isn't that complicated...)
printf("%s", my_str);
return 0;
}
Output (as expected) is "hello world!"
Is there a simpler way, or a built-in function that does this?
PS. An answer in C++ (that handles C-strings) would be fine too
In C++, you can use the overloaded + operator for strings.
std::string my_str;
... // here you calculate the contents of my_str
my_str = "\"" + my_str + "\"";
If you are obliged to use a char array for some reason, you should convert it to a string first:
char my_str[100];
... // here you calculate the contents of my_str
auto new_my_str = "\"" + std::string(my_str) + "\"";
Here, either the first or the second string should be a C++ string (i.e. std::string and not a char array), to make the overloaded operator work.
In C++14, you can use a string literal to make the first string the correct type, using the s suffix:
char my_str[100];
... // here you calculate the contents of my_str
auto new_my_str = "\""s + my_str + "\"";
If you also want your output in the same char array, use c_str and strcpy on the resulting C++ string. You can even fit it into one line of code:
char my_str[100];
... // here you calculate the contents of my_str
strcpy(my_str, ("\""s + my_str + "\"").c_str());
This code is vulnerable to buffer overflow, unlike all the previous ones.
I suppose that the source array already contains a string. Otherwise you could build the string in quotes very easy from scratch.
Here you are.
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[100] = "Hello World";
size_t n = strlen( s );
memmove( s + 1, s, n );
s[0] = '\"';
s[n+1] = '\"';
s[n+2] = '\0';
puts( s );
return 0;
}
The program output is
"Hello World"
In C++ if to use the template class std::string then the same task can be done the following way
#include <iostream>
#include <string>
int main()
{
std::string s( "Hello World" );
s.reserve( s.size() + 2 );
s.insert( 0, 1, '\"' );
s += '\"';
std::cout << s << std::endl;
return 0;
}
Otherwise if you deal with a character array that contains a string then the approach will be the same as it is shown for C.
This is quite simple. Just start with a string that holds the opening quote:
char my_str[100] = "\"";
strcat(my_str, "Hello, world!");
strcat(my_str, "\"");
Or, if you don't want to initialize the string that way, just copy the opening quote:
char my_str[100];
strcpy(my_str, "\"");
strcat(my_str, "Hello, world!");
strcat(my_str, "\"");
Is there a built-in function that acts like strcat from the string start?
Yes, it is called strcat. What you would do in the normal case, is simply to create a second string:
char arr1[N] = "hello world";
char* use_this = arr1;
puts(use_this);
char arr2[N] = "\"";
strcat(arr2, use_this);
use_this = arr2;
strcat(use_this "\"");
puts(use_this);
Trying to be "smart" and save memory by doing this in-place is probably not a good idea, since it comes at the expense of execution speed.
As a side note, your code won't compile on a standard C compiler, because there is no function called "strrev" in the C language. It is a non-standard extension and should therefore be avoided.
There is an easier way - just shift the existing string the required amount of space to make room for the string you want to prepend. Since the source and target areas of memory are overlapping you can't use strcpy or memcpy, but instead have to use memmove
memmove(my_str+1,my_str,strlen(my_str)+1);
and then replace the first character with the double quote.
my_str[0]='\"';
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);
This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 8 years ago.
I am trying to create a string that calls functions and concatenates the return string values. If one of the functions returns an int I get an error. I don't have much experience with overloading operators, but I'm thinking I need to overload the + operator to make this work. Is this correct? Or is there a better way to do this?
string str=getString1()+getString2()+getInt();
You can use std::to_string.
string str = getString1() + getString2() + std::to_string(getInt());
Using std::to_string as suggested by vincent you could also overload the + operator in an easy way:
// string + int
std::string operator+(const std::string &str, const int &i){
std::string result = str + std::to_string(i);
return result;
}
// int + string
std::string operator+(const int &i, const std::string &str){
std::string result = std::to_string(i) + str;
return result;
}
Then your original code should work as espected.
string str = getString1() + getString2() + getInt();
Example:
td::cout << string("This is a number: ") + 5 << endl;
std::cout << 5 + string(" is a number.") << endl;
Output:
This is a number: 5
5 is a number.
I am trying to convert my string into a const char that can be used with the strtok function. What am I doing wrong?
int _tmain(int argc, _TCHAR* argv[])
{
char * pointer_char;
int pos = 0;
std::string str = " Hello good sirtttttt..!.";
int i = 0;
int length = str.length();
const char * cstr = str.c_str();
cout << "Testing string is " << str << endl << endl;
pointer_char = strtok (str.c_str()," ,.;-!?##$%^&");
}
Do not use .c_str() result with strtok directly.
strtok needs char* not a constant and it tries to change the passed string. Since your passed string comes from a const char* then it's not possible to change it. If you try to cast it to a non-const type before passing it to this function then undefined behavior will be invoked.
You need to make a copy and then pass that copy to strtok, for example:
char *c = strdup(str.c_str()); // It's not standard but simple to write
pointer_char = strtok(c," ,.;-!?##$%^&");
free(c);
Try not to use strtok specially in C++ (you have many alternatives), it is not thread safe.
strtok doesn't take const char * as first parameter it takes a char*. The string has to be modifiable.
char *strtok (char *str, const char *delimiters);
str
C string to truncate.
Notice that this string is modified by being broken into smaller strings (tokens).
Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
I need to put "hello world" in c.
How can I do this ?
string a = "hello ";
const char *b = "world";
const char *C;
string a = "hello ";
const char *b = "world";
a += b;
const char *C = a.c_str();
or without modifying a:
string a = "hello ";
const char *b = "world";
string c = a + b;
const char *C = c.c_str();
Little edit, to match amount of information given by 111111.
When you already have strings (or const char *s, but I recommend casting the latter to the former), you can just "sum" them up to form longer string. But, if you want to append something more than just string you already have, you can use stringstream and it's operator<<, which works exactly as cout's one, but doesn't print the text to standard output (i.e. console), but to it's internal buffer and you can use it's .str() method to get std::string from it.
std::string::c_str() function returns pointer to const char buffer (i.e. const char *) of string contained within it, that is null-terminated. You can then use it as any other const char * variable.
if you just need to concatenate then use the operator + and operator += functions
#include <string>
///...
std::string str="foo";
std::string str2=str+" bar";
str+="bar";
However if you have a lot of conacatenation to do then you can use a string stream
#include <sstream>
//...
std::string str1="hello";
std::stringstream ss;
ss << str1 << "foo" << ' ' << "bar" << 1234;
std::string str=ss.str();
EDIT: you can then pass the string to a C function taking a const char * with c_str().
my_c_func(str1.c_str());
and If the C func takes a non const char * or require ownership you can do the following
char *cp=std::malloc(str1.size()+1);
std::copy(str1.begin(), str2.end(), cp);
cp[str1.size()]='\0';