【问题标题】:Error ~ Check if character is lowercase letter错误~检查字符是否为小写字母
【发布时间】:2017-02-05 12:34:53
【问题描述】:

这是我为检查 [i] 是否为小写字母而编写的代码。

    #include<iostream>
    #include<conio.h>
    #include<stdio.h>
    using namespace std;
    int main()
    {
       int i=0;
       char str[i]="Enter an alphabet:";
       char i;
       while(str[i])
            {
              i=str[i];
              if (islower(i))  i=toupper(i);
              putchar(i);
              i++;
            }
       return 0;
     }

我得到的错误是

    ||=== Build: Debug in practice (compiler: GNU GCC Compiler) ===|
    C:\Users\Public\Documents\krish\practice\main.cpp||In function 'int main()':|
    C:\Users\Public\Documents\krish\practice\main.cpp|9|error: conflicting declaration 'char i'|
    C:\Users\Public\Documents\krish\practice\main.cpp|7|note: previous declaration as 'int i'|
    ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

【问题讨论】:

  • 在不相关的注释中,您并不需要 islower 检查。 std::toupper 如果参数不是小写字母,则返回未修改的参数。
  • 以后,请尝试真正阅读错误信息。信息很清楚。

标签: c++ lowercase


【解决方案1】:

问题正是错误消息所说的:您声明i 两次。一次是char,一次是int

int i=0; // declare i as int and assign 0
char str[i]="Enter an alphabet:";
char i; // declare i as char -> i is already declared as int.

重命名变量之一。

也不要使用conio.h - 它不是标准 C 库的一部分,也不是 POSIX 定义的。

【讨论】:

  • 哪个版本的 C++ 允许零大小的数组?
【解决方案2】:

数组在编译时必须有一个恒定的大小和一个非零大小:

int i = 0;
char str[i] = "Enter an alphabet:"; //

您的代码中的上述i 必须是常量,不能是0

所以你可以这样声明它:

const int SIZE = 50;
char str[SIZE] = "Enter an alphabet:";

也在这里:

char i;
while(str[i])

上面你使用i 没有初始化它你使用char 作为数组的索引!

您的代码如下所示:

    const int SIZE = 50; // constant size
    char str[SIZE] = "Enter an alphabet:";

    //if you want : char str[] = "Enter an alphabet:";

    int i = 0; // initialize
    while( i < strlen(str))
    {
        char c = str[i];
        if(islower(c))
            c = toupper(c);
        putchar(c);
        i++;
    }

【讨论】:

    【解决方案3】:

    新代码~~~

        /* islower example */
          #include <stdio.h>
          #include <ctype.h>
          int main ()
          {
           int i=0;
           char str[]="Test String.\n";
           char c;
           while (str[i])
            {
             c=str[i];
             if (islower(c)) c=toupper(c);
             putchar (c);
             i++;
            }
           return 0;
           }
    

    现在开始工作了~~

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 2018-02-03
      • 2012-02-06
      • 1970-01-01
      • 2014-02-12
      • 2017-03-10
      • 1970-01-01
      相关资源
      最近更新 更多