6

I've tried many ways to do that, I got a void which is static and is on Console class i made, Void it self works fine:

Console::WriteLine(const char* msg)

On the other side, I got another const char* non static void which calls the Console::WriteLine void from It, I've been working on C# for around a year and on C# I can easily do something like this:

string a = "Start ";
string b = a + "End";

When i call this on C++, it gives me bunch of errors:

Player::Kill(const char* Message)
{
    Console::WriteLine("> " + Message + " <");
}

I've also tried the strcat thing and put, But it tells me to use strcat_s which doesn't really work, And also I've tried to do string instead of const char*, And tried char*, But all of them give errors for the thing I'm trying to do.

111WARLOCK111
  • 857
  • 2
  • 7
  • 14
  • 7
    Use `std::string`. – Rapptz Sep 02 '13 at 20:22
  • @Rapptz As you can see on above, I've already tried the std string lib, But it gives me error. – 111WARLOCK111 Sep 02 '13 at 20:24
  • 1
    What error does it give you? – Jonathan Potter Sep 02 '13 at 20:24
  • @WARLOCK, You'll have to be more specific. It's the right way to do it. If it's `WriteLine` taking a `const char *`. make it take a `const std::string &`. – chris Sep 02 '13 at 20:24
  • `strcat` operates on `char*` , not `std::string` – Erbureth Sep 02 '13 at 20:25
  • 1
    Welcome to Stack Overflow. To get the best responses, in addition to showing the research you have done and when possible an [sscce](http://sscce.org/), you should try to post the full text of the compiler errors you are getting. Please see the [how to ask questions](http://stackoverflow.com/questions/how-to-ask) section. – kfsone Sep 02 '13 at 20:28
  • The `Console::WriteLine` seems to indicate that you're using something like Managed C++ or C++/CLI or C++/CX. You probably want to edit the tags to reflect the one you're really using. – Jerry Coffin Sep 02 '13 at 20:28
  • I really need a standardized (linkable) rant on "I got a void". No, you don't. `void` is a permanently incomplete type, there never have been nor ever will exist any instances of `void`. What you have is **a function whose return type is `void`**, and if you want to shorten that, say "a function". – Ben Voigt Sep 02 '13 at 21:03

6 Answers6

9

"const" means "cannot be changed(*1)". So you cannot simply "add" one const char string to another (*2). What you can do is copy them into a non-const character buffer.

const char* a = ...;
const char* b = ...;

char buffer[256]; // <- danger, only storage for 256 characters.
strncpy(buffer, a, sizeof(buffer));
strncat(buffer, b, sizeof(buffer));

// now buffer has the two strings joined together.

Your attempt to use std::string failed for a similar reason. You said:

std::string a = "Start";
std::string b = a + " End";

This translates to

b = (std::string)a + (const char*)" End";

Which should be ok except that it creates an extra string, what you probably wanted is

std::string a = "Start";
a += " End";

If you are getting compile errors doing this, please post them (Make sure you #include ).

Or you could do something like:

std::string addTwoStrings(const std::string& a, const std::string& b)
{
    return a + b; // works because they are both strings.
}

All of the following work: (see live demo http://ideone.com/Ytohgs)

#include <iostream>
#include <string>

std::string addTwoStrings(const std::string& a, const std::string& b)
{
    return a + b; // works because they are both strings.
}

void foo(const char* a, const char* b)
{
    std::string str = a;
    std::cout << "1st str = [" << str << "]" << std::endl;
    str += " ";
    std::cout << "2nd str = [" << str << "]" << std::endl;
    str += b;
    std::cout << "3rd str = [" << str << "]" << std::endl;
    str = addTwoStrings(a, " ");
    std::cout << "4th str = [" << str << "]" << std::endl;
    str = addTwoStrings(str, b);
    std::cout << "5th str = [" << str << "]" << std::endl;
}

int main()
{
    foo("hello", "world");
}

*1 Or more accurately, "cannot be changed in-situ" - you can use it in expressions, etc, so for example, e.g.

const size_t len = strlen("hello");
size_t newLen = len + strlen("world");
// but this would not be legal:
len += 2; // error: len is const.

2 "const char a + const char* b" is actually trying to add two pointers not two strings, the result would be the address of string a plus the address of string b, the sum of which would be some random memory location

kfsone
  • 23,617
  • 2
  • 42
  • 74
  • const means you cannot save the result in that variable (const char) or location (const char *). The problem he has with the + is the fact that two pointers cannot be added together (`const char *a, *b, *c; c = a + b;` a and b are pointers and + is not valid between pointers, now `c = a + 10;` works perfectly). Nothing to do with const per se. The result is passed to a function anyway. Also your second example works just fine: `a + " End"` is perfectly valid when a is an std::string. `" End"` is a const char * and it is used as a read-only input string! – Alexis Wilke Sep 03 '13 at 18:03
  • Also incorporated changes to the second string example per your comments. – kfsone Sep 03 '13 at 18:07
  • 1
    @WARLOCK For the sake of correctness, it has actually nothing to do with "const". It's just that you can't add pointers (when you write `"> " + Message` the left operand `"> "` is converted to `const char*` i.e. a pointer). But the operator `+` is [overloaded](http://en.cppreference.com/w/cpp/string/basic_string/operator%2B) notably for `(string, string)` but also for combinations `(string, const char*)` and `(const char*, string)` so `string b = a + " End";` actually [works fine](http://ideone.com/hEGwsu) (even if `a` is `const`). (@kfsone downvote is not from me) _Edit: wow 3 new comments!_ – gx_ Sep 03 '13 at 18:08
  • Weird - it doesn't show edited, but I could have sworn I got the "const char*" a and b and attempts to use strcat etc from the post. Maybe I picked those up from an answer that's been deleted. – kfsone Sep 03 '13 at 18:22
  • @kfsone That's possible indeed, as a post (answer or question, initial or edit) can be modified by its author within 5 minutes after submission without "leaving a trace" in the revision history (and that's how "fast" comments can appear "off topic" afterwards ^^) – gx_ Sep 03 '13 at 19:04
3

char * is a pointer (so are "> " and " <"), you cannot add pointers together.

However you can concatenate C++ strings using the + operator:

Player::Kill(const std::string& Message)
{
    Console::WriteLine(("> " + Message + " <").c_str());
}
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
2

Instead of concatenating the strings and creating an extra temporary object, why not just output the 3 strings separately?

Player::Kill(const char* Message)
{
  Console::Write("> ");
  Console::Write(Message);
  Console::WriteLine(" <");
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

Since you say it's C++ code, just just this:

void Player::Kill(std::string const& Message)
{
    Console::WriteLine(("> " + Message + " <").c_str());
}

Ideally, your Console::WriteLine() is declared to also take a std::string const& in which case you don't need to do the .c_str()-dance.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
-1
#include <iostream>
using namespace std;

string string1 = "John";
string string2 = "Smith";

float string1Len = string1.length();
float combinedLen = string1.length() + string2.length();
char combine[string2.length() + string1.length()];

for(int i = 0; i < string1Len; ++i){
    combine[i] = string1[i];
}
for(int i = string1Len; i < combinedLen; ++i){
    combine[i] = string2[i - string1Len];
}

const char * combined = combine;
David
  • 1
  • 1
-1

well, it is possible to make changes with const char* ,even thought it is const we cannot change its value but can change its address ,check below class for reference

    class String
{
private:
    const char* m_Name;
    int m_Size;
public:
    String() :m_Name(" "), m_Size(0) { m_Size = 0; }
    String(const char* name , int size) :m_Name(name),m_Size(size) {}
    String(const char* name) :m_Name(name) {}

    void Display()
    {
        LOG(m_Name);
    }
    int GetSize()
    {
        while (m_Name[m_Size] != '\0')
        {
            m_Size++;
        }
        return m_Size;
    }
    void Append(const char* nameToAppend)
    {
        //Create an empty char array pointer "*tempPtr" of size = existing const 
        //char name pointer "m_Name"  + const char pointer appending name 
        //"*nameExtention" 
        
        //this array can store both the names 
        int totalSize = 0;
        int nameToAppendSize = 0, existingNameSize = 0;
        while (nameToAppend[nameToAppendSize] != '\0')
        {nameToAppendSize++;}
        existingNameSize = this->GetSize();
        totalSize = nameToAppendSize + existingNameSize;
        char* tempPtr = new char[totalSize+1];

        //Add  existing const char name pointer "*m_Name"  +  const char pointer 
        //appending name "*nameExtention" to tempPtr,  using a loop 
        
        int currentSize = 0;
        for (int i = 0; i < existingNameSize; i++)
        {   
            tempPtr[currentSize] = m_Name[i];
            currentSize++;
        }
        for (int i = 0; i <= nameToAppendSize; i++)
        {
            if (i == nameToAppendSize)
            {
                tempPtr[currentSize] = '\0'; // this line tells compiler to stop 
                                             //  writting inside tempPtr 
            }
            else
            {
                tempPtr[currentSize] = nameToAppend[i];
                currentSize++;
            }
        }
        //--------------------------------
        //Now change the address of your const char* with tempPtr
        //This will change the contents of the const char* 
        //--------------------------------
        m_Name = (char*)tempPtr;
    }
};