AKKO AKKO - 3 months ago 17
C Question

Behavior not understood in C program that prints out initials

I have a simple C program that is supposed to accept a name given by a user and then print out the initials of the name in standard output. My implementation is as follows:

#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(int argc, string argv[])
{
string name = GetString();
printf("%c\n", name[0]); // print out the very first initial of the complete name

for(int i = 1; i< strlen(name); i++)
{
string blank_space = " ";
printf("name[i] = %c \n", name[i]);
printf("i = %d, blank_space = %s,strcmp = %d\n", i, blank_space, strcmp(&name[i - 1], blank_space));
if (strcmp(&name[i - 1], blank_space) == 0)
{
printf("%c\n", name[i]);
}
else
{
continue;
}
}

return 0;
}


If I give the program something like
Aug Koh
as input, then it should give me back
AK
as output. However, when I try debugging my program, I cannot seem to figure what is wrong with it. Here's the standard output from my program:

jharvard@ubuntu (~/pset2): ./initials
Aug Koh
A
name[i] = u
i = 1, blank_space = ,strcmp = 1
name[i] = g
i = 2, blank_space = ,strcmp = 1
name[i] =
i = 3, blank_space = ,strcmp = 1
name[i] = K
i = 4, blank_space = ,strcmp = 1
name[i] = o
i = 5, blank_space = ,strcmp = 1
name[i] = h
i = 6, blank_space = ,strcmp = 1


All it does is it prints out
A
. What really puzzles me is why
strcmp(&name[i - 1], blank_space)
returns a value of
1
even in the case when
name[i - 1]
is a blank space, which should evaluates as the same as
blank_space
variable when doing
strcmp
. When I print out both of them with
printf
they both look the same!

Any help my problem here will be greatly appreciated, and I greatly value any suggestions for improvement.

FYI: This is actually from problem set 2 of the Edx course CS50. So
cs50.h
is a header file that is provided during the course which gives us special types like
string
and unique functions like
GetString()
.

Answer

The less invasive change for your program (and there are many points to discuss) is to change strcmp into strncmp . Because strcmp compares strings of equal length as equal. With strcmp that will never happen because the first parameter string is always longer than the second (space). As your loop will never find the space, only the first letter will be printed.

Change:

   if (strcmp(&name[i - 1], blank_space) == 0)

to

   if (strncmp(&name[i - 1], blank_space,1) == 0)

If you want to compare substrings or

   if( name[i-1]==blank_space )

if you want to compare single letters.

Comments