I am preparing for my Computer Science practical examination, when I hit this roadblock. The following C code is to capitalize all the words in a string taken from the user.
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
char a[20];
int i;
printf("Enter a string: ");
scanf("%[^\n]s",a);
if(islower(a[0])!=0)
{
a[0]=toupper(a[0]);
}
for(i=0;i<strlen(a);i++)
if(a[i]==' ' && isalpha(a[i+1]!=0))
a[i+1]=toupper(a[i+1]);
printf("%s\n",a);
return 0;
}
But the above code doesn't perform the task. It takes the input, but gives the same output(the entered string, as is). Also, there are no errors or warnings shown. I am coding in Ubuntu 14.04 using gcc. I don't seem to understand as to why the code doesn't work.
Your error is with isalpha(a[i+1]!=0)
, as you should simply check isalpha(a[i+1])
. The return-value of the expression a[i+1]!=0
is 1 for all the characters in the input string, except for the last one. The return-value of isalpha(1)
is 0, and so the statement under the if
condition will execute only for the last character, and only if that character is preceded by a space character.
Having said that, here is a better way for you to implement the whole thing:
for (i=1; a[i]!=0; i++)
if (a[i-1]==' ' && isalpha(a[i]))
a[i] = toupper(a[i]);