C++ 将 int 转换为 ASCII 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4629050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:59:14  来源:igfitidea点击:

Convert an int to ASCII character

c++cascii

提问by user963241

I have

我有

int i = 6;

and I want

而且我要

char c = '6'

by conversion. Any simple way to suggest?

通过转换。有什么简单的建议方法吗?

EDIT:also i need to generate a random number, and convert to a char, then add a '.txt' and access it in an ifstream.

编辑:我还需要生成一个随机数,并转换为一个字符,然后添加一个 '.txt' 并在 ifstream 中访问它。

回答by Eugene Mayevski 'Callback

Straightforward way:

直截了当的方式:

char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char aChar = digits[i];

Safer way:

更安全的方法:

char aChar = '0' + i;

Generic way:

通用方式:

itoa(i, ...)

Handy way:

方便的方法:

sprintf(myString, "%d", i)

C++ way:(taken from Dave18 answer)

C++ 方式:(取自 Dave18 的回答)

std::ostringstream oss;
oss << 6;

Boss way:

老板方式:

Joe, write me an int to char converter

乔,给我写一个 int 到 char 转换器

Studboss way:

站长方式:

char aChar = '6';

字符 aChar = '6';

Joe's way:

乔的方式:

char aChar = '6'; //int i = 6;

字符 aChar = '6'; //int i = 6;

Nasa's way:

美国宇航局的方法:

//Waiting for reply from satellite...

//等待卫星回复...

Alien's way: '9'

外星人的方式:'9'

//Greetings.

//你好。

God's way:

大神之道:

Bruh I built this

Bruh 我建了这个

Peter Pan's way:

彼得潘的方法:

char aChar;

switch (i)
{
  case 0:
    aChar = '0';
    break;
  case 1:
    aChar = '1';
    break;
  case 2:
    aChar = '2';
    break;
  case 3:
    aChar = '3';
    break;
  case 4:
    aChar = '4';
    break;
  case 5:
    aChar = '5';
    break;
  case 6:
    aChar = '6';
    break;
  case 7:
    aChar = '7';
    break;
  case 8:
    aChar = '8';
    break;
  case 9:
    aChar = '9';
    break;
  default:
    aChar = '?';
    break;
}

Santa Claus's way:

圣诞老人的方式:

//Wait till Christmas!
sleep(457347347);

Gravity's way:

重力方式:

//What

//什么

'6' (Jersey) Mikes'? way:

'6'(球衣)麦克斯'?道路:

//

//

SO way:

所以方式:

Guys, how do I avoid reading beginner's guide to C++?

伙计们,我如何避免阅读 C++ 初学者指南?

My way:

我的方式:

or the highway.

或高速公路。

Comment: I've added Handy way and C++ way (to have a complete collection) and I'm saving this as a wiki.

评论:我添加了 Handy 方式和 C++ 方式(以获得完整的集合),并将其保存为 wiki。

Edit: satisfied?

编辑:满意?

回答by abelenky

This will only work for int-digits 0-9, but your question seems to suggest that might be enough.

这仅适用于整数 0-9,但您的问题似乎表明这可能就足够了。

It works by adding the ASCII value of char '0'to the integer digit.

它的工作原理是将 char 的 ASCII 值添加'0'到整数数字上。

int i=6;
char c = '0'+i;  // now c is '6'

For example:

例如:

'0'+0 = '0'
'0'+1 = '1'
'0'+2 = '2'
'0'+3 = '3'

Edit

编辑

It is unclear what you mean, "work for alphabets"? If you want the 5th letter of the alphabet:

不清楚你的意思是“为字母工作”?如果您想要字母表的第 5 个字母:

int i=5;
char c = 'A'-1 + i; // c is now 'E', the 5th letter.

Note that because in C/Ascii, A is considered the 0th letterof the alphabet, I do a minus-1 to compensate for the normally understood meaning of 5th letter.

请注意,因为在 C/Ascii 中,A 被认为是字母表的第 0 个字母,所以我做了一个减 1 来补偿通常理解的第 5 个字母的含义。

Adjust as appropriate for your specific situation.
(and test-test-test!any code you write)

根据您的具体情况进行适当调整。
(和测试测试测试!你写的任何代码)

回答by Nathan S.

Just FYI, if you want more than single digit numbers you can use sprintf:

仅供参考,如果您想要多于一位的数字,您可以使用 sprintf:

char txt[16];
int myNum = 20;
sprintf(txt, "%d", myNum);

Then the first digit is in a char at txt[0], and so on.

然后第一个数字在 txt[0] 处的字符中,依此类推。

(This is the C approach, not the C++ approach. The C++ way would be to use stringstreams.)

(这是 C 方法,而不是 C++ 方法。C++ 方法是使用字符串流。)

回答by aleksandar kamenjasevic

My way to do this job is :

我做这项工作的方法是:

    char to int
    char var;
    cout<<(int)var-48;

    int to char
    int var;
    cout<<(char)(var|48);

And i write these functions for conversions

我编写了这些转换函数

int char2int(char *szBroj){
    int counter=0;
    int results=0;
    while(1){
        if(szBroj[counter]=='
unsigned int temp = 6;
or you can use unsigned char temp = 6;
unsigned char num;
 num = 0x30| temp;
'){ break; }else{ results*=10; results+=(int)szBroj[counter]-48; counter++; } } return results; } char * int2char(int iNumber){ int iNumbersCount=0; int iTmpNum=iNumber; while(iTmpNum){ iTmpNum/=10; iNumbersCount++; } char *buffer=new char[iNumbersCount+1]; for(int i=iNumbersCount-1;i>=0;i--){ buffer[i]=(char)((iNumber%10)|48); iNumber/=10; } buffer[iNumbersCount]='
unsigned char num,code;
code = 0x39; // ASCII Code for 9 in Hex
num = 0&0F & code;
'; return buffer; }

回答by Dorato

This is how I converted a number to an ASCII code. 0 though 9 in hex code is 0x30-0x39. 6 would be 0x36.

这就是我将数字转换为 ASCII 代码的方式。十六进制代码中的 0 到 9 是 0x30-0x39。6 将是 0x36。

int i = 6;
char c[2];
char *str = NULL;
if (_itoa_s(i, c, 2, 10) == 0)
   str = c;

this will give you the ASCII value for 6. You do the same for 0 - 9

这将为您提供 6 的 ASCII 值。您对 0 - 9 执行相同操作

to convert ASCII to a numeric value I came up with this code.

将 ASCII 转换为数值我想出了这个代码。

 std::ostringstream oss;
 oss << 6;

回答by cpx

Alternative way, But non-standard.

替代方式,但非标准。

std::to_string(i)

Or Using standard c++ stringstream

或使用标准 C++ stringstream

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    char numeros[100]; //vetor para armazenar a entrada dos numeros a serem convertidos
    int count = 0, soma = 0;

    cin.getline(numeros, 100);

    system("cls"); // limpa a tela

    for(int i = 0; i < 100; i++)
    {
        if (numeros[i] == '-') // condicao de existencia do for
            i = 100;
        else
        {
            if(numeros[i] == ' ') // condicao que ao encontrar um espaco manda o resultado dos dados lidos e zera a contagem
            {
                if(count == 2) // se contegem for 2 divide por 10 por nao ter casa da centena
                    soma = soma / 10;
                if(count == 1) // se contagem for 1 divide por 100 por nao ter casa da dezena
                    soma = soma / 100;


                cout << (char)soma; // saida das letras do codigo ascii
                count = 0;

            }
            else
            {
                count ++; // contagem aumenta para saber se o numero esta na centena/dezena ou unitaria
                if(count == 1)
                    soma =  ('0' - numeros[i]) * -100; // a ideia é que o resultado de '0' - 'x' = -x (um numero inteiro)
                if(count == 2)
                    soma = soma + ('0' - numeros[i]) * -10; // todos multiplicam por -1 para retornar um valor positivo
                if(count == 3)
                    soma = soma + ('0' - numeros[i]) * -1; /* caso pense em entrada de valores na casa do milhar, deve-se alterar esses 3 if′s
        alem de adicionar mais um para a casa do milhar. */
            }
        }
    }

    return 0;
}

回答by jun

"I have int i = 6; and I want char c = '6' by conversion. Any simple way to suggest?"

“我有 int i = 6; 我想通过转换得到 char c = '6'。有什么简单的建议方法吗?”

There are only 10 numbers. So write a function that takes an int from 0-9 and returns the ascii code. Just look it up in an ascii table and write a function with ifs or a select case.

只有10个数字。所以编写一个函数,它从 0-9 中获取一个 int 并返回 ascii 代码。只需在 ascii 表中查找并使用 ifs 或 select case 编写一个函数。

回答by iceSea

I suppose that

我想

##代码##

could do the job, it's an overloaded function, it could be any numeric type such as int, double or float

可以完成这项工作,它是一个重载函数,它可以是任何数字类型,例如 int、double 或 float

回答by Marcos Freitas Brazil

Doing college work I gathered the data I found and gave me this result:

在做大学工作时,我收集了我发现的数据并给出了以下结果:

"The input consists of a single line with multiple integers, separated by a blank space. The end of the entry is identified by the number -1, which should not be processed."

“输入由一行多个整数组成,由空格分隔。条目的末尾由数字 -1 标识,不应处理。”

##代码##

The comments are in Portuguese but I think you should understand. Any questions send me a message on linkedin: https://www.linkedin.com/in/marcosfreitasds/

评论是葡萄牙语,但我想你应该明白。任何问题都可以在linkedin上给我发消息:https: //www.linkedin.com/in/marcosfreitasds/