Concatenate char arrays in C++ - c++

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;
}

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;
}

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);

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;
}

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
}

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';

cout<<x<<y<<z<<" ";
char arr[3] = {x , y ,z};
ans.push_back(arr);
if you want to push in vector array.

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;

Related

MessageBox string with variable name value dev c++ [duplicate]

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;
}
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;
}
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);
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;
}
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
}
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';
cout<<x<<y<<z<<" ";
char arr[3] = {x , y ,z};
ans.push_back(arr);
if you want to push in vector array.
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;

C++ error cannot specify explicit initializer for arrays for char g[]

I have the declared the following struct:
const struct DATABASE_ALREADY_EXISTS {
const int Code = 2001;
const char Str[] = "Database already exists.";
};
But then when I pass it to the function:
DATABASE_ALREADY_EXISTS DB_ERR;
error_output(DB_ERR.Str, DB_ERR.Code);
It throws the following error(Visual Studio 2013):
cannot specify explicit initializer for arrays
Here is the declaration error_output:
template<class D>
char* error_output(D err_str, int err_code = 0)
{
return "(" + err_code + ") " + err_str;
}
How should I change the definition Str member of the struct to eliminate such error?
I think you can modify your code like below; As return "(" + err_code + ") " + err_str; doesnt make any sense, you can't apply + operator on two char *'s .
#include <string>
#include <iostream>
#include <cstring>
#include <sstream>
struct DATABASE_ALREADY_EXISTS {
DATABASE_ALREADY_EXISTS(const char* s) : Str(s) {}
static const int Code = 2001;
const char *Str;
};
template<class D>
const char* error_output(D err_str, int err_code = 0)
{
std::istringstream is;
is>>err_code;
std::string str;
str += "(";
str += is.str();
str += ") ";
str += err_str;
return str.c_str();
}
int main(void)
{
DATABASE_ALREADY_EXISTS DB_ERR("Database already exists.");
const char *res = error_output(DB_ERR.Str, DB_ERR.Code);
std::cout<<res<<std::endl;
return 0;
}
#include <iostream>
using namespace std;
struct Error {
private:
static char Buf[1024];
public:
int Code;
char* Str;
char* DisplayString() const {
sprintf_s(Buf, 1024, "(%d) %s", Code, Str);
return Buf;
}
friend ostream& operator<<(ostream& os, const Error& rhs) {
return os << rhs.DisplayString();
}
};
char Error::Buf[1024];
#define DEC_ERROR(name, code, str) Error name = { code, str }
DEC_ERROR(DATABASE_ALREADY_EXISTS, 2001, "Database already exists.");
DEC_ERROR(UNICORN_WITHOUT_HORN, 2002, "Unicorns should have a horn.");
int _tmain(int argc, _TCHAR* argv[]) {
cout << DATABASE_ALREADY_EXISTS << endl;
cout << UNICORN_WITHOUT_HORN << endl;
}
Outputs:
(2001) Database already exists.
(2002) Unicorns should have a horn.

how to reverse char array using class member pointer?

im tryin to reverse an array using pointer which is a class member:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class my_string
{
char* ptr;
int size;
public:
my_string(){};
my_string(char* str) : ptr(str),size(strlen(ptr)){};
char* getstr () {return ptr;};
void reverse();
int find (char);
void print();
};
void my_string::reverse()
{
int size2=size;
for (int i=0;i<(size/2);i++)
{
char tmp=ptr[i];
ptr[i]=ptr[size2-1];
ptr[size2-1]=ptr[i];
size2--;
}
}
int my_string::find(char c)
{
for (int i=0;i<size;i++)
{
if (ptr[i]==c)
return i;
}
return -1;
}
void my_string::print()
{
for (int i=0;i<size;i++)
cout<<ptr[i];
cout<<endl;
}
int main()
{
my_string s1("abcde");
s1.print();
s1.reverse();
s1.print();
}
im not gettin any errors but the reverse function is surely not working.
can someone please explain to me why?
*this is an homework assignment asking me not to use dynamic allocation or strings (for now).
You didn't mention not being able to use standard library algorithms, so
std::reverse(ptr, ptr+size);
You can use standard algorithm std::reverse declared in header <algorithm>.
For example
std::reverse( ptr, ptr + size );
But if you want to do it yourself then the function could look the following way
void my_string::reverse()
{
for ( int i = 0; i < size/2; i++ )
{
char tmp = ptr[i];
ptr[i] = ptr[size-1-i];
ptr[size-1-i] = tmp;
}
}
A test program
#include <iostream>
#include <cstring>
int main()
{
char s[] = "123456789";
char *ptr = s;
int size = std::strlen( ptr );
std::cout << s << std::endl;
for ( int i = 0; i < size/2; i++ )
{
char tmp = ptr[i];
ptr[i] = ptr[size-1-i];
ptr[size-1-i] = tmp;
}
std::cout << s << std::endl;
}
Output is
123456789
987654321

How to declare the Char array of char variables already declared in class?

#include <stdio.h>
#include <iostream>
using namespace std;
//char* b[6] = new char[6];
char a[6] = {'b','c','d','e','f','g'};
char c[6] = {'a','b','d','d','f','g'};
int main()
{
char d[][6]={*a,*c};
for (int x = 0 ; x < 1; x++)
{
for(int y = 0; y<6; y++)
{
char test = d[x][y];
cout << test <<"\n";
}
}
return 0;
}
This code is C++ code. I am trying to create a class where it stores the char array. Then there is another char array of array storing already declared char variables. It compiles fine but it doesn't work out to as it should. It doesn't get me the right value that it should when the program tries to print the value
May be you meant array of pointers:
char *d[]={a,c};
typedef std::vector<char> VectorChar;
typedef std::vector< VectorChar* > VectorVectorChar;
struct V
{
V() : _v{ '0', '1', '2' } {}
VectorChar _v;
};
int main(void)
{
V arrV[5];
VectorVectorChar vvc;
for ( auto& v : arrV )
vvc.push_back( &v._v );
// print them
for ( auto pV : vvc )
{
for ( auto c : *pV )
cout << c << ' ';
cout << '\n;
}
return 0;
}
what i understood from the question that, you want to create class to store char array, which already initialized.
#include <stdio.h>
#include <iostream>
char a[6] = {'b','c','d','e','f','g'}; // Initialized character array. MAX 6
// This class will hold char array
class Test {
public:
void setName(char *name);
const char* getName();
private:
char m_name[6]; // MAX 6 ( since you already initialized(MAX 6), So no need dynamic memory allocation. )
};
void Test::setName(char *name) {
strcpy(m_name, name); // Copy, already initialized array
}
const char* Test::getName() {
return m_name;
}
int main(int argc, char** argv) {
{
Test foobar;
foobar.setName( a ); // set the pointer which point to starting of the initialized array.
cout << foobar.getName();
return 0;
}
char a[6] = {'b','c','d','e','f','\0'};
char c[6] = {'a','b','d','d','f','\0'};
char* d[]= {a,c};
for (int x = 0 ; x < 2; x++)
{
for(int y = 0; y < 6; y++)
{
char test = d[x][y];
cout << test << "\n";
}
}
return 0;

Mysterious error; private variable of C++ class not printing its value even after initialization

I have made a class String which has two private members int length and a character pointer.
There are two constructors which initialize these members.
My question why s1.print() is not working in my code?
#include <iostream>
#include <string.h>
using namespace std;
class String {
int length;
char * ptr;
public:
String(int N, char s[]) {
ptr = new char[N];
strcpy(s, ptr);
}
String(int N) {
ptr = new char[N];
}
String concat(String s2) {
String result(s2.length + length, strcat(ptr, s2.ptr));
}
void print(void) {
cout << ptr << endl;
}
};
int main() {
char temp[50];
cin >> temp;
String s1(strlen(temp) + 1, temp);
//String s2(strlen(temp)+1, temp);
s1.print();
//s1.concat(s2);
//s1.print();
return 0;
}
In order to print the char* you need to cast it to string and than print.
Another thing I suggest that your array size will be N + 1 and add a NULL-terminate at ptr[N] = '\0'