0

I am having a problem with targeting the first character after any space(" ") in a string. I want to target the character so that I may capitalize it with toupper. Is there a way I can do this? If so, what is it? I have inserted an attempt below.

int main(void){

printf("Please enter your name! \n");
string s = GetString();

for (int i=0;i <1; i++)
{
    printf("%c", toupper(s[0]));
    printf("%c", toupper(char *strstr(const char *s, const char (" ")+1));
}
printf("\n");

}

2 Answers 2

1

It's unclear what you are trying to do with your for loops since 1) it does not advance i (i.e. it will be stuck at 0 since it ends when i<1 which is 0) and 2) you do not reference i anywhere inside your loop. I think what you are trying to do, and which is probably the easiest way to accomplish this task, is to use a for loop to advance through your string s, checking each element to see if it is a space. Here's how your for loop would look like:

for (int i=0; i<len(s); i++)
  {
  if (s[i]==" ")
  //then get character in position i + 1 and capitalize it
  }

Hope this helps.

0
0

So when I execute the following code.

int main(void){

for (int i=0;i <strlen(s); i++)
{
if (s[i]==" ")
    printf("%d", toupper(s[i+1]));
printf("%d", toupper(s[1]));}

I get the following error. I understood why I had to use strlen(s) and thank you for that one. However i'm not sure I got the second part correctly.


clang -fsanitize=integer -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wshadow initials.c -lcrypt -lcs50 -lm -o initials

initials.c:13:13: error: result of comparison against a string literal is unspecified (use strncmp instead) [-Werror,-Wstring-compare] if (s[i]==" ") ^ ~~~

initials.c:13:13: error: comparison between pointer and integer ('int' and 'char *') [-Werror] if (s[i]==" ") ~~~~^ ~~~ 2 errors generated. make: *** [initials] Error 1

2
  • Since space is a character, and we are in c environment where, a character and string are enclosed in different quotes. Try to use; if (s[i]==' ') instead of if (s[i]==" ") Commented Nov 15, 2016 at 18:09
  • @ApoorvAgnihotri is of course right, good catch.
    – ronga
    Commented Nov 17, 2016 at 3:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .