I'm working on the hacker edition of pset2 and I'm running into a problem with initials.c
Here's the spec: Write, in a file called initials.c, a program that prompts a user for their name (using GetString to obtain their name as a string) and then outputs their initials in uppercase with no spaces or periods, followed by a newline (\n) and nothing more. You may assume that the user’s input will contain only letters (uppercase and/or lowercase) plus spaces. Folks like Joseph Gordon-Levitt, Conan O’Brien, and David J. Malan won’t be using your program. But the user’s input might be sloppy, in which case there might be one or more spaces at the start and/or end of the user’s input or even multiple spaces in a row.
So that we can automate some tests of your code, your program must behave per the examples below.
username:~/workspace/hacker2 $ ./initials
Zamyla Chan
ZC
username:~/workspace/hacker2 $ ./initials
robert thomas bowden
RTB
When I run ./initials in the terminal, everything runs correctly, but check50 displays an error:
:( outputs "MB" for " milo banana "
\ expected output, but not "MB\u0000\n"
:( outputs "MB" for " milo banana "
\ expected output, but not "MB\u0000\n"
Here's my original code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
// Get name from user usng GetString
// printf("Please enter your name: ");
string name = GetString();
// Check for NULL
if (name!=NULL)
{
// Print first initial if it's not whitespace
if (!isspace(name[0]))
{
printf("%c", toupper(name[0]));
}
/**
* Iterate over the length of the string
* Pass over spaces and print initials
*/
for (int i=0, n=strlen(name); i<n; i++)
{
if (isspace(name[i]) && !isspace(name[i+1]))
{
printf("%c", toupper(name[i+1]));
}
}
}
printf("\n");
}
I know that the problem is here in my for loop:
if (isspace(name[i]) && !isspace(name[i+1]))
{
printf("%c", toupper(name[i+1]));
}
When it gets to the end of string such as " milo banana " that ends in a space, check50 thinks it prints [n+1] which is the NULL terminating character \u0000. However it doesn't actually show up in the output, at least not in my terminal window.
I have attempted multiple fixes, but none of them work:
1. Adding:
if (isspace(name[i]) && (i+1)>n)
{
break;
}
2. Adding an else if condition:
else if (isspace(name[i]) && name[i+1] == '\0')
{
// NOTHING
}
Any thoughts?