-1

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

This is not working for me in the below example.

I need my output to be converted to its character values, but after using char(int), its still giving output using the int datatype only.

#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;
  }
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Sagar0807
  • 3
  • 2
  • d[i] = char(c[i]); need to modify this so my output array d[i] contains only characters converted from ASCII int values – Sagar0807 Apr 11 '17 at 16:56
  • its not duplicate question, can someone please give the exact specific answer instead of just marking it as duplicate like @Remy Lebeau – Sagar0807 Apr 11 '17 at 17:22

1 Answers1

0

Your code fails because you are storing the values in an int[] array. d[i]=char(c[i]); is useless because all you are doing is converting an int to a char back to an int again. You are then outputting the array values as-is as int values instead of converting them back to actual char values.

Try something more like this instead:

#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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770