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
Change strcat(e,c) to strncat(e, &c, 1)
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;
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;