我在输出句子大小写字符时遇到问题。当我提示时:
你好!你好。我还好。

我期望输出:
你好!你好。我还好。

但是我的示例运行输出是:
你好!你好。我还好。

我的代码在'!'/'.'/'?'/'_'之后不能输出大写
有人可以告诉我我犯了什么错误吗?提前致谢。

-艾莉

样例代码:

printf ("\n\nThe line of the text in sentence case is:\n");

i = 0;
text_ptr = text;
up = 1;                 /* up = 1 means upper case is yes */
while ( *(text_ptr+i) != '\0')  /* could have been: while(text[i]) */
{
    if(!up)
        if( *(text_ptr+i-1)==' ' && toupper(*(text_ptr+i)=='I' && (*(text_ptr+i+1)==' ' ||
                *(text_ptr+i+1)=='.' || *(text_ptr+i+1)=='!' || *(text_ptr+i+1))=='?') )
        up = 1;     /* capitalize i if all alone */

    if(up)
        if (*(text_ptr+i)!=' ' || *(text_ptr+i+1)=='.' || *(text_ptr+i+1)=='!' || *(text_ptr+i+1)=='?')
        {
            putchar(toupper(*(text_ptr++)));
            up = 0;
        } /* end if */
        else
            putchar(tolower(*(text_ptr++)));
    else
    {
        putchar(tolower(*(text_ptr+i)));
        if (*(text_ptr)=='?' || *(text_ptr)=='.' || *(text_ptr)=='!')
            up = 1;
        i++;
    } /* end else */
}/* end while */`

最佳答案

再来一次。在看了一些代码之后,我看到了


您操纵了指针text_ptr++
仅在循环的i部分增加else
打印text_ptr++text_ptr+i


...很难理解的地方所以我完全修订了我的版本:

int i  = 0;
int up = 1; /* up = 1 means next char should be upper case*/
char* text_ptr = text;

while (*(text_ptr+i) != '\0') { /* could have been: while(text[i]) */
    if(!up)
      if(*(text_ptr+i-1)==' ' && toupper(*(text_ptr+i))=='I' &&
        (*(text_ptr+i+1)==' ' || *(text_ptr+i+1)=='.' ||  // fix bracket here
         *(text_ptr+i+1)=='!' || *(text_ptr+i+1)=='?')) { // "i" foll. by one of those
           up = 1;    /* capitalize i if all alone */
      }

    if(up)
      if (*(text_ptr+i)!=' ' && *(text_ptr+i)!='.' && // fix here
          *(text_ptr+i)!='!' && *(text_ptr+i)!='?') { // anything else than these
            putchar(toupper(*(text_ptr+i))); // toupper and reset up
            up = 0;
        } /* end if */
        else
            putchar(tolower(*(text_ptr+i))); // just print
    else
    {
        putchar(tolower(*(text_ptr+i)));
        if (*(text_ptr+i)=='?' || *(text_ptr+i)=='.' || *(text_ptr+i)=='!')
            up = 1;
    } /* end else */
    i++;
}/* end while */


请注意,此版本确实需要toupper。否则,正确的I将降低。您的第四个if也可以正常工作(我监督,您不会重置up标志的空格)。

09-30 14:43
查看更多