【问题标题】:c++ that make an upper case in array to lowerc++ 使数组中的大写字母变小
【发布时间】:2023-02-09 00:12:25
【问题描述】:

我正在编写一个程序,将大写数组转换为小写,然后反转 降低阵列。

#include <iostream>
using namespace std;

int main()
{
    char upper[10];
    cout << "Please enter a string" << endl;
    cin >> upper;
    int ascii;
    ascii = upper;  #error is here it says a value of type char cannot be assigned to int
    ascii = ascii + 32;
}


【问题讨论】:

  • 我确定错误实际上是说它无法将数组转换为 int - 因为您将如何定义这样的转换?
  • 您需要一个循环或一个循环函数,对upper 中的每个字符执行转换。你目前两者都没有。循环将在您的语言参考中广泛涵盖。

标签: c++


【解决方案1】:

您正在尝试将 char[10] 的数组分配给 int,这显然是不兼容的类型。您可能打算处理数组中的每个人char,您可以通过以下方式完成:

for(char c : array)
{
    int ascii = static_cast<int>(c) + 32;
    std::cout << ascii << std::endl;
}

请注意,您的“转换为小写”算法假定您的字符集是 ASCII,并且 array 将只包含大写 ASCII 字符。

【讨论】:

    【解决方案2】:

    此代码将无法编译,因为读取“ascii = upper;”的代码行将一个 char 类型的值(用户输入的字符串)赋值给一个 int 变量。要解决此问题,您可以使用函数 toupper() 将字符转换为对应的大写字母,然后再将其分配给 int 变量。或者,您可以使用函数 tolower() 将字符转换为对应的小写字母,然后再将其分配给 int 变量。

    尝试这个:

    #include <iostream>
    #include <cctype>
    using namespace std;
    
    int main()
    {
        char upper[10];
        cout << "Please enter a string" << endl;
        cin >> upper;
        int ascii;
        ascii = toupper(upper); 
        ascii = ascii + 32;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      相关资源
      最近更新 更多