For instance...

say that I set

char a = 'a'
char b = 'b'

how would I combine them to make them "ab" using strcat?

Dani AI

Generated

asked how to make "ab" from two char variables. This is a common confusion: a single char (for example char a = 'a';) is a scalar value, not a C-string. As points out, strcat/strncat operate on null-terminated character arrays (C-strings), so they require writable buffers with room for the characters plus the terminating '\0'. is also right that in C++ std::string is the easier, safer choice.

Practical options (safe and different from the code already posted):

  • Use snprintf (C): allocate a buffer large enough for both chars plus '\0' and format into it.
#include <stdio.h>

char a = 'a', b = 'b';
char out[3];                /* 2 chars + terminating NUL */
snprintf(out, sizeof out, "%c%c", a, b);
/* out == "ab" */
  • Use strncat correctly (C): always start with a writable destination that is null-terminated and compute remaining space.
#include <string.h>

char a = 'a', b = 'b';
char dest[3] = "";          /* must be a writable array */
char tmp[2]  = { a, '\0' }; /* single-character C-string */
strncat(dest, tmp, sizeof dest - strlen(dest) - 1);
  • Use std::string (C++): push characters into a string rather than using C APIs.
#include <string>

std::string s;
s.push_back(a);
s.push_back(b);  // s == "ab"

Quick safety tips: destination buffers must hold combined length + 1; strncat's third argument is the max number of characters to append (not the total dest size); never call strcat on string literals or uninitialized storage. For most C++ code prefer std::string; for C prefer snprintf or careful malloc/size checks.

Recommended Answers

All 2 Replies

You can't because both those functions only work on null-terminated strings. In your example, neither a nor b has enough room to hold more than one character. Then could be contantinated like this:

char a = 'a';
char b = 'b';
char all[3];
all[0] = a;
all[1] = b;
all[2] = '\0';

Well, in your example you can't, because strcat requires two char*, whereas a and b are simple chars. What you can do is to work with strings:

#include <iostream>
#include <string>
using namespace std;
int main(){
   char a='a';
   char b='b';
   const char* all;
   string together;
   together+=a;
   together+=b;
   all=together.c_str();
   cout<<all;
   return (0);
}

or

int main(){
    char a='a';
    char b='b';
    string together;
    together.insert(together.begin(), a);
    together.insert(together.begin()+1, b);
    cout<<together;
    return (0);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.