const char* concatenation
In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:
strcat(one,two); // append string two to string one.
will not work. Instead you should have a separate variable(char array) to hold the result. Something like this:
char result[100]; // array to hold the result.
strcpy(result,one); // copy string one into the result.
strcat(result,two); // append string two to the result.
Why concatenation of two const char* is not allowed in C++?
With two literal strings, you can concatenate them, but you don't need any operator, just (optional) spaces. So
std::string s="hello" "world";
is allowed and the same as
std::string s="helloworld";
Actually, at parsing time, two literal strings are glued together as one. And this also applies to C and happens after preprocessing expansion.
This is phase 6 of the compilation process. Adjacent string literals are concatenated.
BTW, this only works with string literals. E.g.
std::string s1= ((1<2)?"hello":"goodbye") "world"; // wrong
std::string s2= ("ab")"cd"; // wrong
are both wrong.
You might also use the operator ""s
using std::literals::string_literals;
std::string s= "abcd"s + "ef"s;
but then both "abcd"s
and "ef"s
denote some constant std::string
-s and the +
applies to these.
Why c++ standard library developers decide not to reload"+" to implement a char* concatenation?
Then you would want to code
char* foo = (rand()%4)?"lucky":"unlucky";
char* bar = foo + "xy"; // wrong
and if such a +
was implemented, it would need to allocate heap memory (at runtime) à la strdup
and you would need to decide who and when would that be delete[]
or free
-d. BTW, as r0ng answered you cannot define an operator +
on pointer types. So the standard committee decision to not allow that is sane.
However if you replace char*
above twice with std::string
it works.
Initialize const char* by concatenating another char*
Compiling the comments in the form of an answer:
Use a macro.
#define QUICK "quick "
char const* arr = "The " QUICK "brown";Use
std:string
.std::string quick = "quick ";
std::string arr = std::string("The ") + quick + "brown";
Working code:
#include <iostream>
#include <string>
#define QUICK "quick "
void test1()
{
char const* arr = "The " QUICK "brown";
std::cout << arr << std::endl;
}
void test2()
{
std::string quick = "quick ";
std::string arr = std::string("The ") + quick + "brown";
std::cout << arr << std::endl;
}
int main()
{
test1();
test2();
}
Output:
The quick brown
The quick brown
How concatenate a string and a const char?
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 string
s (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.
How to concatenate const char* strings in c++ with no function calls?
First, there is nothing null
terminated, but the zero terminated. All char* strings in C end with '\0'
.
When you in code do something like this:
char *name="Daniel";
compiler will generate a string that has a contents:
Daniel\0
and will initialize name
pointer to point at it at a certain time during program execution depending on the variable context (member, static, ...).
Appending ANYTHING to the name
won't work as you expect, since memory pointed to by name
isn't changeable, and you'll probably get either access violation error or will overwrite something else.
Having
const char* copyOfTheName = name;
won't create a copy of the string in question, it will only have copyOfTheName
point to the original string, so having
copyOfTheName[6]='A';
will be exactly as
name[6]='A';
and will only cause problems to you.
Use std::strcat
instead. And please, do some investigating how the basic string operations work in C.
Concatenating integers to const char* strings
The type of a string literal like "file"
is char const[N]
(with a suitable N
) whic happily decays into a char const*
upon the first chance it gets. Although there is no addition defeined between T[N]
and int
, there is an addition defined between char const*
and int
: it adds the int
to the pointer. That isn't quite what you want.
You probably want to convert the int
into a suitable std::string
, combine this with the string literal you got, and get a char const*
from that:
load(("file" + std::to_string(i)).c_str());
Why can't I concat 2 const char* to a std::string?
The technical reasons for not having such an operator are centred around ownership (what would own this operator? std::string
, the global namespace, or something else), the fact that adding two const char*
pointers makes no sense, and other issues centred around the properties of read-only NUL-terminated character literals.
"Hello" + " World"
knows nothing about what it's about to be assigned to. The use of the +
requires the const char[]
literals to decay to const char*
pointers. Adding two pointers makes no sense at all and so modern compilers will issue a diagnostic stating that +
is not defined for const char[]
types.
"Hello" " World"
is the C-idiomatic string literal concatenation syntax. That's been around since the 1970s and helps folk write long strings when there were only 80 or so characters visible per line of code.
hello + " World"
is using the overloaded +
operator on std::string
. That's because hello
is a std::string
.
From C++14 onwards you could exploit user defined literals with
std::string str = "Hello"s + " World";
or even
std::string str = ""s + "Hello" + " World";
Note the suffixed s
.
How to concat two const char*?
1.
const char* p=new char[strlen(metadata.getRoot())+strlen(metadata.getPath())+1];
the length plus 1 to store '\0'.
2.
strcpy(const_cast<char*>(args2->fileOrFolderPath),p);
You can not guarantee args2->fileOrFolderPath
's length is longger than strlen(p)
.
This works well
#include <iostream>
using namespace std;
void foo(const char*s){
cout<<s<<endl;
}
int main(int argc,char*argv[]){
const char* s1 = "hello ";
const char* s2 = "world!";
const char* p = new char [strlen(s1)+strlen(s2)+1];
const char* s = new char [strlen(s1)+strlen(s2)+1];
strcat(const_cast<char*>(p),s1);
strcat(const_cast<char*>(p),s2);
strcpy(const_cast<char*>(s),p);
cout<<s<<endl;
foo(s);
return 0;
}
Related Topics
Error: Passing 'Const …' as 'This' Argument of '…' Discards Qualifiers
When Do I Use Fabs and When Is It Sufficient to Use Std::Abs
Should C++ Eliminate Header Files
Why Do Some People Prefer "T Const&" Over "Const T&"
What's the C++ Suffix for Long Double Literals
What Does 'Using Std::Swap' Inside the Body of a Class Method Implementation Mean
How to Fix: /Usr/Lib/Libstdc++.So.6: Version 'Glibcxx_3.4.15' Not Found
Why Isn't 'Std::Initializer_List' Defined as a Literal Type
Platform-Independent Guid Generation in C++
I Want to Kill a Std::Thread Using Its Thread Object
C++, How to Call a Constructor Directly, Without New
Performance Penalty for Working with Interfaces in C++
How to Use an Enum Value in a Switch Statement in C++
Can You Allocate a Very Large Single Chunk of Memory ( > 4Gb ) in C or C++