0

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

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

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

我的代码在 '!'/'.'/'?'/'_' 之后无法输出大写字母,谁能告诉我我犯了什么错误?提前致谢。

-艾莉

示例代码:

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 */`
4

1 回答 1

0

再次。在对代码进行了更多关注之后,我看到了

  • 你操纵了指针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为空格重置标志)。

于 2015-03-14T10:03:50.820 回答