简体   繁体   中英

how can I strcat one character to array character in c++

I want to get one character from cin.get() and add it to a array character. I use strcat but the single character has an error. please help me if you know. thanks for all answers.

void main (void)
{
 char e[80]="hi";
 char c;
 cin.get(c);
 strcat(e,c);
 cout << "e: " << e << endl;
 getch();
}

This is part of my code that I want to do this.

stncat() concatenates two strings, method signature looks like this,

char * strncat ( char * destination, const char * source, size_t num );

but you are trying to concatenate a char which is not right!

As you are using C++, it is safe and easy to do it in C++ style rather than using C style.So use

std::string cAsStr(c);   // Make the string
e += aAsStr;             // + operator does the concatenation 

If you are desperate to do it in the C style, use:

char cAsStr[] = { c, '\0' }; // Making a C-style string
strcat(e, cAsStr);           // Concatenate

将strcat(e,c)更改为strncat(e,&c,1)

char s[] = { c, 0 };
strcat(e, s);

But please, just use std::string :

string e="hi";
char c;
cin.get(c);
e += c;
cout << "e: " << e << endl;

A little change to your code would do it.

char e[80]="hi";
char c[2] = {0}; // This is made as an array of size 2
cin.get(c[0]); // Character is read into the first position.
strcat(e,c);
cout << "e: " << e << endl;

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