This was an exercise from cs50. The goal was to get the initials in upper letter of a name that we got from user. So for "barack obama" we would get "BO", input like "abc" should output "A" and so on. I am interested in knowing what I can do to simplify it or be more efficient.
Do I need the check against '\0'
in the while
loop? I ask because the way I see it, when a user inputs a name, there will always be a '\n'(right ?), so it gets out of the while
loop when its position has '\n'
and then out of for loop so '\0'
is never actually checked. Let me know if logic is right. I kept it there just in case.
#include <stdio.h>
#include <ctype.h>
#define NAME_LEN 80 + 1
int main(void)
{
char userName[NAME_LEN], userInitials[NAME_LEN];
int i, pos = -1;
// ask user for a name
fgets(userName, NAME_LEN, stdin);
for(i = 0; userName[i] != '\n' && userName[i] != '\0'; i++)
{
if (userName[i] >= 'a' && userName[i] <= 'z')
{
userInitials[++pos] = userName[i] - ('a' - 'A');
}
else
{
userInitials[++pos] = userName[i];
}
while ((!isblank(userName[i])) && (userName[i] != '\n') && (userName[i] != '\0'))
{
i++;
}
}
userInitials[++pos] = '\0';
printf("%s\n", userInitials);
}
fgets
, there won't be a\n
. \$\endgroup\$