rebbailey rebbailey - 2 months ago 15
C Question

Character not saving to array

I am asking the user to input a string. I would like to output the first letter of each word in uppercase.

Example:

barack hussein obama
=>
BHO


Currently this is my attempt:

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

int main(void){
string user_name = GetString();

int word_counter = 0;
int counter = 0;

// Get length of string.
for(int i = 0; i < strlen(user_name); i++){
if(strncmp(&user_name[i], " ", 1) == 0){
word_counter += 1;
}
}
word_counter += 1;


// Declare empty array and size.
char output[word_counter];

// Iterate through array to assign first characters to new array.
for(int i = 0; i < strlen(user_name); i++){
if(i == 0){
output[counter] = toupper(user_name[i]);
counter += 1;
}
else if(strcmp(&user_name[i - 1], " ") == 0){
output[counter] = toupper(user_name[i]);
counter += 1;
}
}

// Output result.
for(int i = 0; i < word_counter; i++){
printf("%c\n", output[i]);
}

printf("\n");
}


When the output returns, I only receive
B
. It seems that output is not saving the first letters of each word. Am I declaring output incorrectly?

Answer

strcmp(&user_name[i - 1], " ") Is not just comparing 1 char as inteneded (like your original strncmp(&user_name[i], " ", 1) does).

Why use str[n]cmp() anyway, why not just if (name[i] == ' ') { ... ?

Comments