3

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.

4

3 回答 3

2

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);
于 2013-03-30T23:53:49.123 回答
2

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.

于 2013-03-30T23:53:57.393 回答
0

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.

于 2013-03-31T17:58:48.430 回答