Reputation: 9
Help! I am writing a program in C to grab all the initials - I know nothing about pointers so lets try to stay away from those - this is what I have so far:
#include <stdio.h>
//CS50 Library for 'get_string() user input'
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void){
printf("Enter your name: ");
//User input for string
string s = get_string();
int i = 0;
//Determine whether the first chars are space - if not print char
if(s[0] != isspace(s[0])){
printf("%c",s[0]);
}
//loop through each Char - determine char is not space
while(s[i] != '\0'){
if(s[i] == ' '){
//if i'th char is space - add one to it thus printing char that comes after space
printf("%c", toupper(s[i+1]));
}
//advance i'th char count
i++;
}
printf("\n");
}
When I input "John Gerald Smith" the program comes back with "JGB", but if I attempt to enter something like: " John gerald smith"(multiple spaces), It appears to not remove any of the spaces. I still get the initials for output but I need to make sure it does NOT print any spaces at all. Please Help! This is homework so I don't expect to just be handed the answer but if anyone could give me some information on how about doing that I would much appreciate it. Thanks!
Upvotes: 0
Views: 253
Reputation: 29266
I'd approach it differently to the original and the answer by @yajiv by avoiding "special case code" for the first char in the string.
I'd take one run through the list and uses some "state" to know when to output a character.
When we see a space we know that we want to output the next non space (so we set printNextNonSpace
)
When we see a non space we print it if printNextNonSpace
is set (and then we clear printNextNonSpace
to avoid printing extra chars)
printNextNonSpace
is initially set to 1 so we print the first char in the string if it isn't a space.
Note that this will handle any number of spaces anywhere in the string "Andrew Bill Charlie" -> "ABC"
, " David Edgar Frank " -> "DEF"
[code removed as OP wisely wanted hints not answer on a platter]
Upvotes: 1
Reputation: 2941
#include <stdio.h>
//CS50 Library for 'get_string() user input'
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void){
printf("Enter your name: ");
//User input for string
string s = get_string();
int i = 0;
//Determine whether the first chars are space - if not print char
if(!isspace(s[0])){
printf("%c",s[0]);
}
i++;
//loop through each Char - determine char is not space
while(s[i] != '\0'){
if(s[i-1]==' ' && s[i] != ' '){
//if i'th char is space - add one to it thus printing char that comes after space
printf("%c", toupper(s[i]));
}
//advance i'th char count
i++;
}
printf("\n");
}
First it checks weather previous character is space or not, if it is space then it check whether the current character is space or not and if it is not space print the current character otherwise not.
Hope this helps.
Upvotes: 0