需要我当前的字符输出,这是它在C++中的整数值

Need my current output in Characters which are its int values in C++

本文关键字:C++ 整数 输出 字符      更新时间:2023-10-16

d[i] = char(c[i]);

在下面的示例中,这对我不起作用。

我需要将我的输出转换为其字符值,但是在使用 char(int) 之后,它仍然仅使用 int 数据类型给出输出。

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    cin>>str;
    int size=str.size();
    int len=0;
    if (size % 2 == 0)
    {
        len=size/2;
    }
    else
    {
        len=(size/2)+1;
    }
    int a[len],b[len],c[len],d[len],x,y;
    int i=0,j=size-1;
    while(i<len)
    {
        x=(int)str[i];
        y=(int)str[j];
        if (i == j)
        {
            a[i]=x;
        }
        else
        {
            a[i]=x+y;
        }
        b[i]=a[i]%26;
        c[i]=x + b[i];
        d[i]=char(c[i]);
        cout<<"l : "<<d[i]<<endl;
        i++;
        j--;
    }
    return 0;
  }

代码失败,因为您将值存储在 int[] 数组中。 d[i]=char(c[i]);是没有用的,因为您所做的只是将int转换为char,然后再转换为int。然后,将数组值按原样输出为int值,而不是将它们转换回实际的char值。

尝试更多类似的东西:

#include <vector>
#include <string>
using namespace std;
int main()
{
    string str;
    cin >> str;
    int size = str.size();
    int len = (size / 2) + (size % 2);
    // VLAs are a non-standard compiler extension are are not portable!
    // Use new[] or std::vector for portable dynamic arrays...
    //
    // int a[len], b[len], c[len];
    // char d[len];
    //
    std::vector<int> a(len), b(len), c(len);
    std::vector<char> d(len);
    int x, y, i = 0, j = (size-1);
    while (i < len)
    {
        x = (int) str[i];
        y = (int) str[j];
        if (i == j)
        {
            a[i] = x;
        }
        else
        {
            a[i] = x + y;
        }
        b[i] = a[i] % 26;
        c[i] = x + b[i];
        d[i] = (char) c[i];
        cout << "l : " << d[i] << endl;
        ++i;
        --j;
    }
    return 0;
}