如何为每个字的第一个字母C中的数组 [英] How to capitalize the first letter of each word in an array in C

查看:191
本文介绍了如何为每个字的第一个字母C中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个简单的程序,在大多数80个字符数组存储用户输入的句子,然后在大写的句子每个单词。我觉得我在正确的轨道上,但是当我运行程序时,只显示句子的第一个字。

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;
}

我有一种感觉它只是打印第一个字的数组中,因为第一,如果scanf函数后声明,但我不能完全确定。任何帮助将是AP preciated。谢谢你。

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.

推荐答案

默认情况下,%S 转换说明会导致scanf函数停止在第一个空格字符。因此,您既可以使用 80%[^ \\ n] 格式或与fgets 功能。

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);

或者

#include <stdio.h>

fgets(sen, sizeof sen, stdin);

不过,由于 scanf函数读的格式的数据的,人力投入是不适合这样的读数。因此,与fgets 应该在这里好。

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

这篇关于如何为每个字的第一个字母C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆