user2228214
user2228214

Reputation:

How to capitalize the first letter of each word in an array in C

I am trying to make a simple program that stores a user-input sentence in an array of at most 80 characters and then capitalizes each word of in the sentence. I think I'm on the right track, however when I run the program, only the first word of the sentence is displayed.

#include<stdio.h>
 int main(void)
{   
 int i;         /*indexing integer*/
 char sen[81]; /*specify total of 80 elements*/
 printf("Enter a sentence no longer than 80 characters: \n\n");
 scanf("%s",sen);
 if((sen[0]>='a') && (sen[0]<='z'))
 {
  sen[0]=(char)(sen[0]-32); /*-32 in ascii to capitalize*/
 }
  for(i=0;sen[i]!='\0';i++)   /*loop until null character*/
  {
  if(sen[i]==' ')             /*if space: next letter in capitalized*/
   {
    if((sen[i+1]>='a') && (sen[i+1]<='z'))
    sen[i+1]=(char)(sen[i+1]-32);
   }
  }
  printf("%s",sen);     
  return 0;
}

I have a feeling it is only printing the first word in the array because of the first if statement after the scanf, but I am not completely sure. Any help would be appreciated. Thanks.

Upvotes: 3

Views: 3891

Answers (3)

Darshan Shah
Darshan Shah

Reputation: 67

dont use scanf when you want to take multiple words as input: use either gets() or fgets().. I run your code with gets() and puts() and it worked.

Upvotes: 0

md5
md5

Reputation: 23707

By default, the %s conversion specifier causes scanf to stop at the first whitespace character. Therefore you could either use the %80[^\n] format or the fgets function.

#include <stdio.h>

scanf("%80[^\n]", sen);

Or:

#include <stdio.h>

fgets(sen, sizeof sen, stdin);

However, since scanf reads formatted data, human inputs are not suitable for such readings. So fgets should be better here.

Upvotes: 2

user529758
user529758

Reputation:

I have a feeling it is only printing the first word in the array because of the first if statement after the scanf

No, that's because the %s specifier makes scanf() scan up to the first whitespace. If you want to get an entire line of text, use fgets():

char sen[81];
fgets(sen, sizeof(sen), stdin);

Upvotes: 2

Related Questions