Reputation: 7
I've cut out a lot of the code to make it easier to read. Specifically I'm trying to rewrite strcat
#include <iostream>
using namespace std;
char MYstrcat(char string1[],char string2[]);
int main()
{
char letter, letter_ans, again;
const int SIZE = 80;
char string1 [SIZE];
char string2 [SIZE];
getting input for the character arrays
cout << "Enter the first string: ";
cin >> string1;
cout << "Enter the second string: ";
cin >> string2;
letter_ans=MYstrcat(string1, string2);
cout << letter_ans;
cin.get(); cin.get();
return 0;
}
this is my version of the strcat function
char MYstrcat(char string1[],char string2[])
{
int i = 0; //Counters
int j = 0;
//Read until null character is encountered then append.
while (string1[i] != '\0')
{
i++;
}
while (string2[j]!= '\0'){
string1[i] = string2[j];
i++;
j++;
}
string1[i]='\0'; // Place a null character in string2.
i get the error in this next line: invalid conversion from 'char*' to 'char'
return string1;
}
Upvotes: 1
Views: 230
Reputation: 3440
The function header char MYstrcat(char string1[],char string2[]);
declares the return type as char, but the function body is returning a string. return string1;
Upvotes: 1
Reputation: 517
because string1 is an char array. ie:char[]... but your function's return type is char . so you got an error.you can change you function's return type to char*, then test your code. good luck.
Upvotes: 0
Reputation: 3968
char MYstrcat(char string1[],char string2[]); // returns a single character
char *MYstrcat(char string1[],char string2[]); // returns a pointer to a string that can be used like string1[] and string2[]
Likewise,
char letter_ans; // this gives space for a single char, like int int_ans;
char *letter_ans; // this makes a pointer to an array of char's, the proper return type
However, since you are returning string1, it may be possible that you don't even want to use a return type. If you declare your function as so:
void MYstrcat(char *string1,char *string2);
It will operate directly on string1, leaving no need to return a pointer to it.
Upvotes: 3
Reputation: 73433
Arrays decompose in to pointers in C++, so when you do return String1
you are returning a char*
, hence the return type of your function should be char*
.
Upvotes: 2