我必须写简短的脚本,将int转换为ASCII char和char转换为ASCII int。但我不知道怎么做。我写了这个简短的代码,但有些东西是错误的。我已经编程半年了。有人能写出来吗?这是我第一次在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;
}
非常感谢大家,我已经用更短的代码完成了。
#include <iostream>
using namespace std;
int main(){
int a=68;
cout<<char(a);
char c='D';
cout<<int(c);
return 0;
}
您也可以使用printf,因此您不需要创建其他函数来转换数字。
int i = 64;
char c = 'a';
printf("number to ascii corresponding to %d is %cn", i, i);
printf("ascii to number corresponding to %c is %dn", c, c);
输出将是
number to ascii corresponding to 64 is A
ascii to number corresponding to a is 97
也许您可以从下面的代码开始。如果这是不完整的,你可以用测试用例来完成你的问题吗?
#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;
}
输出为:
number to ascii corresponding to 97 is a or a
ascii to number corresponding to H is 72 or 72
#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;
}
输出:
char corresponding to number 97 is 'a'
number corresponding to char 'H' is 72'
原来我以为你只是想转换数字:您可以简单地在char和char中添加和减去'0':
char toChar(int n) {
return n + '0';
}
int toInt(char c) {
return c - '0';
}
如果您只想强制转换类型,请阅读