how can I strcat one character to array character

2019-07-22 04:40发布

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.

4条回答
乱世女痞
2楼-- · 2019-07-22 04:50

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;
查看更多
ら.Afraid
3楼-- · 2019-07-22 04:53

Change strcat(e,c) to strncat(e, &c, 1)

查看更多
混吃等死
4楼-- · 2019-07-22 05:01
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;
查看更多
Anthone
5楼-- · 2019-07-22 05:05

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
查看更多
登录 后发表回答