Concatenate Strings

y can't we concatenate strings using strcat?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

main()
{
    string fname("Jeson");
    string lname("Borne");
    string fullname;
    
    strcat(fullname,lname);
    strcat(fullname,fname);
    
    cout<<fullname;
    cin.ignore();
    cin.get();
}
Because strcat is for C strings.

String concatenation works like this:
string fullname=lname+" "+fname;
Because strcat accepts pointers to char. You are not passing it pointer to char - you are trying to pass it a std::string

http://www.cplusplus.com/reference/clibrary/cstring/strcat/

If a function takes one kind of object as an input parameter, you cannot simply give it something else completely and expect it to work.

If you want to concatenate std::string objects, use the '+' operator.

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

int main()
{
    string fname("Jeson");
    string lname("Borne");
    string fullname;
    
    fullname = fname + lname;    
    cout<<fullname;

   return 0;
}

So The conclusion is to concatenate strings we must use the + operator.

strcat can be used only in chars.
Am i right?
No. strcat can only be used for pointers to char.
@Moschops

Just to make sure I understand what you are saying(I am not OP), by pointers to char you are speaking about char arrays right? Because aren't char arrays addresses(like when you pass an array to a function, it passes an address?)
Because aren't char arrays addresses(like when you pass an array to a function, it passes an address?)

No, arrays are a set of elements of the same type that are contiguous in memory.
However, they can be implicitly converted to a pointer to their first element.
not only char arrays but also integer arrays can be converted to pointers to their first element.
@georgewashere I don't know much but i think the answer is no.Arrays are set of elements with same data type. when u pass it to a function u pass the elements not the addresses. but if ur using a pointer pointed to that array which is in same data type then you can pass that pointer by differencing it.
1
2
3
4
char name[size]={0};
char *cPtr;
cPtr=name;//note ....same as integer arrays
//cPtr=&name [ 0 ] same as     cPtr =name  

Last edited on
Topic archived. No new replies allowed.