#include<cs50.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main(void)
{
string s = get_string();
{
int n = 0;
printf("%c", toupper(s[n]));
while ( s[n] != ' ' && s[n] != '\0')
{
n++;
}
printf("%c", toupper(s[n + 1]));
int p = n;
while (s[p] == ' ' && s[n] != '\0')
{
p++;
}
int q = p;
while ( s[q] != ' ' && s[q] != '\0')
{
q++;
}
printf("%c", toupper(s[q + 1]));
}
printf("\n");
}
2 Answers
\u0000
is a character escape sequence for a NULL terminator, so you might want to rethink your while loops so that you don't go past the end of the string.
More generally, you should keep your code DRY -- in other words, Don't Repeat Yourself.
Repetition like this is a sign of an inefficient algorithm:
int n = 0;
while ( s[n] != ' ' && s[n] != '\0')
{
n++;
}
int p = n;
while (s[p] == ' ' && s[n] != '\0')
{
p++;
}
int q = p;
while ( s[q] != ' ' && s[q] != '\0')
{
q++;
}
There's absolutely nothing to be gained by declaring three integers for n
, p
, and q
, then doing the exact same thing with them. You can combine and streamline to greatly improve your algorithm.
Think about this pseudo code instead:
int main(void)
{
// prompt user for input (you are doing this correctly)
string s = get_string();
// if not NULL
// print first character of string, no matter what
// convert to uppercase if necessary
// iterate through string, looking for spaces
// instead of a while() loop, consider using a for() loop
// you may find strlen(s) helpful with this approach!
// if we find a space at s[n], print the character at s[n + 1]
// convert to uppercase if necessary
// finally, print the newline.
}
Or maybe pseudo like this:
//get string
//found first letter and print
//while is not end of string do
//if (s[i]==' '&& s[i+1]!=' '&& s[i+1]!='\0')
// {
// printf("%c", toupper(s[i+1]));
// }
// i++;
//print empty string
Good luck! And I'm waiting for your voice ;)}
-
thank you so much, I basically re-did it. but way worse result to be honest. Commented Apr 14, 2017 at 20:03