【问题标题】:why can't I convert all words to uppercase C为什么我不能将所有单词都转换为大写 C
【发布时间】:2014-08-11 21:52:25
【问题描述】:

不知道为什么输入的字符串中的大写字母会变成随机码

#include<stdio.h>
#include<string.h>
#define length 100
int main()
{
   int count;
   char word[length];
   printf("Please input your word =");
   scanf("%s", &word);
   count=strlen(word);
   int i;
   for(i=0;i<=count;i++)
   {
        if(word[i]>=97||word[i]<=122)
        {
           word[i]+= -32;
        }
        printf(" %c",word[i]);
   }
   return 0;
}

【问题讨论】:

  • 请使用 toupper - linux.die.net/man/3/toupper
  • 在 "if(word[i]>=97||word[i]
  • 如果您将其标记为 C++,为什么您的代码是“C”?在 C++ 中将单词转换为大写是单行算法调用。其次,你的循环有一个错误——它的i 上升到&lt;=count。因此,您在不应该的时候使用空终止符。
  • 改用word[i] &gt;= 'a' &amp;&amp; word[i] &lt;= 'z'

标签: c++ c uppercase capitalize


【解决方案1】:

变化:

if(word[i]>=97||word[i]<=122)

收件人:

if(word[i]>=97 && word[i]<=122)

【讨论】:

    【解决方案2】:

    您应该在条件中使用 AND 运算符而不是 OR 运算符。

    if(word[i]>=97 && word[i]<=122)    //to specify small character region's upper AND lower bound
    

    并且可以尝试使用

    word[i] -= 32; //for simplicity
    

    【讨论】:

      【解决方案3】:

      || --------》&&

      #include<stdio.h>
      #include<string.h>
      #define length 100
      int main()
       {
          int count;
          char word[length];
          printf("Please input your word =");
          scanf("%s", word);
          count=strlen(word);
          int i;
          for(i=0;i<count;i++)
             {
                 if(word[i]>=97&&word[i]<=122)
                   {
                      word[i]+= -32;
                   }
                 printf(" %c",word[i]);
        }
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-23
        • 2013-10-05
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        • 2019-02-04
        • 1970-01-01
        • 1970-01-01
        • 2013-12-09
        相关资源
        最近更新 更多