簡體   English   中英

Int 到 ASCII 字符和 char 到 ASCII 數字 | C++

[英]Int to ASCII char and char to ASCII number | C++

我必須編寫簡短的腳本,將 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;
}
#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'

最初我以為您只是想轉換數字:您可以簡單地將 '0' 加減到 char 和 char 中:

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

如果您只想轉換類型,請閱讀此

也許你可以從下面的代碼開始。 如果這不完整,您能否用測試用例完成您的問題?

#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;
}


output 是:

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

您也可以使用 printf,因此您不需要創建其他 function 來轉換數字。

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);

output 將是

number to ascii corresponding to 64 is A
ascii to number corresponding to a is 97

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM