-4

I must write short script which will change int to ASCII char and char to ASCII int. But i don't know how. I wrote this short code but something is wrong. I'm programming for half-year. Can someone write it working? It is my first time to use functions in c++

#include <iostream>
#include <conio.h>

using namespace std;
char toChar(int n) {
return n + '0';
}
int toInt(char c) {
return c - '0';
}
int main()
{
int number;
cout << "Int: ";
cin >> number;
cout << "ASCII: " << static_cast<char>(number);
getch();
return 0;
}

4 Answers4

1

Thank You very much Guys, I have done it with shorter and working code.

#include <iostream>
using namespace std;
int main(){
int a=68;
cout<<char(a);
char c='D';
cout<<int(c);
return 0;
}
0
#include <iostream>

using namespace std;

char toChar(int n)
{
    if (n > 127 || n < 0)
        return 0;
    return (char)n;
}

int toInt(char c)
{
    return (int)c;
}

int main()
{
    int number = 97;
    cout << "char corresponding to number " << number << " is '" <<  toChar(number) << "'\n";

    char car='H';
    cout << "number corresponding to char '" << car << "' is " << toInt(car) << "\n";

    return 0;
}

output:

char corresponding to number 97 is 'a'
number corresponding to char 'H' is 72'

Originally I thought you were just looking to convert the number: You can simply add and substract '0', to char and from char:

char toChar(int n) {
    return n + '0';
}
int toInt(char c) {
    return c - '0';
}

If you just want to cast the type, read this

Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81
0

May be you could start with the code below. If this is incomplete, could you please complete your question with test cases?

#include <iostream>


using namespace std;

char toChar(int n)
{   //you should test here the number shall be ranging from 0 to 127
    return (char)n;
}

int toInt(char c)
{
    return (int)c;
}

int main()
{
    int number = 97;
    cout << "number to ascii corresponding to  " << number << " is " <<(char)number << " or " << toChar(number) <<endl;

    char car='H';
    cout << "ascii to number corresponding to " << car << " is " << (int)car << " or " << toInt(car) << endl;

    return 0;
}


The output is:

number to ascii corresponding to  97 is a or a
ascii to number corresponding to H is 72 or 72

Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27
0

you could also use printf, so you don't need to create other function for converting the number.

int i = 64;
char c = 'a';

printf("number to ascii corresponding to %d is %c\n", i, i);
printf("ascii to number corresponding to %c is %d\n", c, c);

the output is gonna be

number to ascii corresponding to 64 is A
ascii to number corresponding to a is 97
Linus
  • 50
  • 3