15

I have the following code and would like to end up with a char such as: "Hello, how are you?" (this is just an example of what I'm trying to achieve)

How can I concatenate the 2 char arrays plus adding the "," in the middle and the "you?" at the end?

So far this concatenates the 2 arrays but not sure how to add the additional characters to my final char variable I want to come up with.

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    char foo[] = { "hello" };
    char test[] = { "how are" };
    strncat_s(foo, test, 12);
    cout << foo;
    return 0;
}

EDIT:

This is what I came up with after all your replies. I'd like to know if this is the best approach?

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    char foo[] = { "hola" };
    char test[] = { "test" };
    string foos, tests;
    foos = string(foo);
    tests = string(test);
    string concat = foos + "  " + tests;
    cout << concat;
    return 0;
}
Matimont
  • 739
  • 3
  • 14
  • 33
  • 3
    Use `std::string`. It's even easier than your attempt with arrays (which doesn't work at all because arrays have a fixed size). – ghostofstandardspast Jun 17 '14 at 02:57
  • 1
    Unrelated: You're calling `#include `, but doing nothing with std::string(s). You probably should at least be including `#include ` if you're manipulating C style strings. Bit the better solution may be to convert input to std::string type, and if some function requires a c-string, call the `.c_str` method on your std::string. – DavidO Jun 17 '14 at 03:05
  • Why have braces around your stringx – Ed Heal Jun 17 '14 at 03:08
  • 1
    Is there a reason why you are using arrays of `char` to represent your strings? – Drew Dormann Jun 17 '14 at 03:09
  • Just an aside - it's a good idea to output `'\n'` after your output - on some systems the text may not be visible after the program exits unless a final newline is sent (e.g. some UNIX/Linux shells - assuming every program will finish each line with a newline - clear back to the start of line then print the prompt). – Tony Delroy Jun 17 '14 at 03:53
  • Hi Drew, yes, I'm using Char because I'm modifying another code which returns Char and I need to concatenate that with my own generated chars – Matimont Jun 17 '14 at 22:59
  • @Matimont: it's a good idea to get the character the other code returns into a `std::string` immediately, then you can add your own text. Everything's simpler and safer with `std::string`. – Tony Delroy Jun 18 '14 at 02:27
  • All, I added my findings in the EDIT section of my question, it works, but is it the best approach? – Matimont Jun 18 '14 at 14:55
  • @Matimont Being late, I know... I would do it this way: `char* f; char* b; std::string c; c.reserve(strlen(f) + strlen(b) + 2); ((c += f) += ' ') += b;`, i. e. assign the C strings to the std::string directly instead of producing *additional`* copies (foos/tests!), and reserving sufficient memory avoids reallocation within std::string. – Aconcagua Jul 19 '17 at 09:55

7 Answers7

13

In C++, use std::string, and the operator+, it is designed specifically to solve problems like this.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string foo( "hello" );
    string test( "how are" );
    cout << foo + " , " + test;
    return 0;
}
M.M
  • 138,810
  • 21
  • 208
  • 365
quantdev
  • 23,517
  • 5
  • 55
  • 88
8

Best thing is use std::string in C++ as other answers. If you really need to work with char try this way. didn't tested.

const char* foo = "hello";
const char* test= "how are";

char* full_text;
full_text= malloc(strlen(foo)+strlen(test)+1); 
strcpy(full_text, foo ); 
strcat(full_text, test);
Nayana Adassuriya
  • 23,596
  • 30
  • 104
  • 147
  • 3
    Why are you using `malloc` in C++ code? Also you forgot to have space for the null character – Ed Heal Jun 17 '14 at 03:26
  • @EdHeal: Thank you, I added the null character. I have to ask you back, so why `malloc` works in C++ compilers? – Nayana Adassuriya Jun 17 '14 at 03:32
  • 4
    Because it does - originally C++ code was converted into C. But for new code you should use `new`. Also why produce a C code when you have all the extra abilities of C++ – Ed Heal Jun 17 '14 at 03:36
2

If you dont want to use string you can do it simply by taking an other array and storing both arrays in it with loop

#include<iostream>
#include<stdlib.h>
#include<cstdio>
using namespace std;
int main(){
    char fname[30],lname[30],full_name[60];
    int i,j;
    i=0;j=0; // i is index of fname and j is index for lname
    cout<<"Enter your first name: ";
    gets(fname);
    cout<<"Enter your last name: ";
    gets(lname);
    for (i;fname[i]!='\0';i++){
        full_name[i] = fname[i];
    }
    cout<<"i ="<<i;
    full_name[i]=' ';
    i = i + 1;
    for (i,j;lname[j]!='\0';i++,j++){
        full_name[i] = lname[j];
    }
    cout<<"Your full name is: "<<full_name<<endl;
    system("pause");
    return 0;
}
Noman
  • 53
  • 1
  • 7
  • See [Why gets() is so dangerous it should never be used!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used) – David C. Rankin Sep 16 '20 at 07:05
1

Yes, in C++ use the + operator for string concatenation. But this will not work:

char[] + char[] + char[]

convert one array to std::string and it will:

std::string(char[]) + char[] + char[]

E.g.:

#include <iostream>

int main()
{
    const char a[] = "how ";
    const char b[] = "are ";
    const char c[] = "you ";

    std::cout << std::string( a + b + c ) << "\n"; // Error
    std::cout << std::string(a) + b + c  << "\n"; // Fine
}
jav
  • 583
  • 5
  • 15
1

If performance is a concern for you, I would suggest avoiding std::string. Instead, you can use the character array.

template <typename Result>
void concatenate(Result *res)
{
  return;
}

template <typename Result, typename T>
void concatenate(Result *res, T *str)
{
  strcat(res, str);
}

template <typename Result, typename First, typename ... T>
void concatenate(Result *res, First *f, T* ... next)
{
  strcat(res, f);
  concatenate(res, next...);
}

template <typename Result, typename First, typename ... T>
void concatStrings(Result *res, First *f, T* ... next)
{
  strcpy(res, f);
  concatenate(res, next...);
}

And then, you can call the concatStrings function with at least two parameters and at most as many you need.

/* You can remove constexpr as per your need. */
constexpr char hello[6] = "hello";
constexpr char sep[2] = ",";
constexpr char how[5] = " how";
constexpr char are[5] = " are";
constexpr char you[6] = " you?";

auto totalSize = strlen(hello) + strlen(sep) + strlen(how) + strlen(are) + strlen(you) + 5;

char statement[totalSize];
concatStrings(statement, hello, sep, how, are, you);
std::cout << statement << '\n';
  • `std::string` is plenty fast for almost any situation. Playing with arrays is usually only needed when interfacing with other code that plays with arrays. In fact, `std::string` is faster in many common scenarios. For example, finding its size is O(1) for `std::string` and O(n) for a C-style string. Additionally, since `std::string` knows what memory is in use, algorithms can check multiple bytes with a single instruction whereas a C-style string must first check a byte isn't `'\0' to avoid reading invalid memory. – user904963 Dec 22 '21 at 23:54
-1
cout<<x<<y<<z<<" ";
char arr[3] = {x , y ,z};
ans.push_back(arr);

if you want to push in vector array.

-2

FOR 2 CHAR ARRAYS

  char foo[] = { "hello " };
  char test[] = { "how are" };
  char concat[50];
  char x='X'; //Any Temporary Variable
  int i;
  for(i=0; x!='\0'; i++){ //x is not NULL
    x = foo[i];
    concat[i] = x;
  }
  x = 'D';
  i--;
  for (int k = 0; x!='\0'; i++){
    x = test[k];
    concat[i] = x;
    k++;
  }
  cout<<"Concat Array is: "<<concat;