+ 1
I have to print last and second last characters from a word.
eg. when input is APPLE then output should be E L but i am confused with functions written after main(). please help char* lastLetters(char* word) { //what should i write here??? } int main() { FILE *f = stdout; char *output_path = getenv("OUTPUT_PATH"); if (output_path) { f = fopen(output_path, "w"); } char* res; char* word; word = (char *)malloc(512000 * sizeof(char)); scanf("\n%[^\n]",word); res = lastLetters(word); fprintf(f, "%s\n", res); fclose(f); return 0; }
6 Answers
+ 3
i m getting no output
+ 2
return &[(strlen(word)-2]);
I m getting output as LE instead of E L
+ 1
I tried it but it was showing some error and sometimes no output
+ 1
Here you go.
char *res = (char *) malloc(3*sizeof(char));//one extra character to store NULL char.
int i, j;
for(i = 0; word[i] != '\0'; i++) ;
for(j =0; i>=0 && j <2; i--,j++) {
res[j++] = word[--i];
}
res[j] = '\0';
return res;
0
First, using a loop you should traverse till the end of the word. Copy the last two characters from backwards into a new dynamically created array, and then return it. Try implementing this yourself. If you are unable to, I will help you.
0
@Alind, can you show us what you tried?