+ 1

Hi can you set this code the right way?

//program to convert first and last letters of each word in a string to upper case #include <stdio.h> #include <string.h> #include <stdlib.h> int invert_case(char ch); int main() { char str[50]; fgets(str, 50, stdin); int l= strlen(str); printf("input= %s\n", str); int count=0; for(int i=0; i<=l; i++){ if(i==0 || i==l-1){ invert_case(str[i]); count++; continue; } if(str[i]==32){ invert_case(str[i-1]); invert_case(str[i+1]); count++; continue; } } printf("output= %s\nnumber of times invert_case() is called= %d", str, count); return 0; } int invert_case(char ch){ if(ch>='a'&&ch<='z'){ ch= ch-('a'-'A'); } return 0; } //The output is as below input= hello how are you output= hello how are you number of times invert_case() is called= 5 //But the output expected is HellO HoW ArE YoU please help @Gen300

11th May 2020, 9:14 AM
Tom
Tom - avatar
2 Respuestas
+ 2
you can change invert_case() to take pointer to char. Reason is when you pass char by value then the char you pass in is copied for function invert_case(). all changes are made to its local copy but no changes are made outside of invert_case(). so inside invert_case() ch will behave like local variable... there are two ways you can fix it. one is with pointer, the other is without. Method 1: void invert_case(char *ch) { if (*ch >= 'a' && *ch <= 'z') *ch -= ('a' - 'A'); } Method 2: char invert_case(char ch) { if (ch >= 'a' && ch <= 'z') ch -= ('a' - 'A'); return ch; } first method is easier. but you must change all invert_case() inputs to take an address: invert_case(&str[i - 1]); invert_case(&str[i + 1]); if you do second method you must return the char and assign it to the string: str[i - 1] = invert_case(str[i - 1]);
11th May 2020, 11:00 AM
Gen2oo
Gen2oo - avatar
+ 1
thankyou @Gen200
11th May 2020, 3:13 PM
Tom
Tom - avatar