How to add "FINISHED" after a Char

Hi Guys,

I'm a newbie and need some simple advice. I have the following:

char* Buffer = "DATA";

I am trying to add "FINISHED" to the end of "char* Buffer". So it will equal "DATAFINISHED".

Any ideas? All replies will be warmly welcomed!

Many Thanks,

Googie.
What about

std::string buffer = "DATA";

then sometime later,

buffer += "FINISHED";

If you want an actual char* to pass to some legacy function, then you can use buffer.c_str() to get such a pointer.
Hi

Using a std::string is the right way to go in real C++ code, as salem c has suggested. But if you're playing the with old-school C-style char buffers for education purposes, or being somehow forced to write C code, then...

If you want to append a string to the contents of a buffer, you've got to have a buffer to start with. Your "Buffer" variable is not a buffer; it's a pointer to a constant string. So you have nowhere to copy.

Worse than that, the literal string is probably stored in read-only memory, if you were to try and change an element of the string "DATA" you will very probably cause an error (access violation) More modern C++ compilers will not allow code like char* Buffer = "DATA"; -- Microsoft Visual C++ 2019 tells me:

error C2440: 'initializing': cannot convert from 'const char [5]' to 'char *'

But it was allowed in the past to avoid breaking old code, as early C++ compilers were not as careful as they could have been. :-(

char buff[] = "DATA"; or char buff[] { "DATA" };

creates a buffer of length 5 -- length of string plus one for the null terminator (the newer {} syntax is better for modern compilers)

char buff[64] { "DATA" }; // better to use a const for buffer length than literal

creates a buffer of length 64 with 'D', 'A', 'T', 'A' in the first 4 elements and zero chars ('\0') in all other elements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    const int buffSize { 64 };
    char buff[buffSize] { "DATA" }; 

    cout << "before: " << buff << endl;

    strcat(buff, "FINISHED");
    // http://www.cplusplus.com/reference/cstring/strcat/

    cout << "after: " << buff << endl;

    return 0;
}

Output:

before: DATA
after: DATAFINISHED


Andy
Last edited on
Registered users can post here. Sign in or register to post.