简体   繁体   中英

How to combine two character type variables

Consider that iam creating two variables

              char a1,b1,c1; /*consider that im assigning*/

              a1='a',b1='b';

              /* now i want to combine a1 and b1  and assign to c1 
               i.e c1='ab' pls suggest me the code to do that. 
              Dont suggest any complex code im a begineer. 

You can't do with a regular char variable. To do what you want you should use an array of char :

char a1, b1, c1[2];

a1 = 'a';
b1 = 'b';

c1[0] = a1;
c1[1] = b1;

You can't store two characters in a char variable (it has only 1 byte) .

Use a char array and use sprintf or snprintf -

char c1[3];
sprintf(c1,"%c%c",a,b);   // or snprintf(c1,sizeof c1,"%c%c",a,b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM