C++ 将单个字符转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1800875/
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
Convert single char to int
提问by Raptrex
How can I convert char a[0] into int b[0] where b is a empty dynamically allocated int array
如何将 char a[0] 转换为 int b[0] 其中 b 是一个空的动态分配的 int 数组
I have tried
我试过了
char a[] = "4x^0";
int *b;
b = new int[10];
char temp = a[0];
int temp2 = temp - 0;
b[0] = temp2;
I want 4 but it gives me ascii value 52
我想要 4 但它给了我 ascii 值 52
Also doing
也在做
a[0] = atoi(temp);
gives me error: invalid conversion from ‘char' to ‘const char*' initializing argument 1 of ‘int atoi(const char*)'
给我错误:从 'char' 到 'const char*' 的无效转换正在初始化 'int atoi(const char*)' 的参数 1
回答by Gonzalo
You need to do:
你需要做:
int temp2 = temp - '0';
instead.
反而。
回答by Dave S.
The atoi() version isn't working because atoi() operates on strings, not individual characters. So this would work:
atoi() 版本不起作用,因为 atoi() 对字符串而不是单个字符进行操作。所以这会起作用:
char a[] = "4";
b[0] = atoi(a);
Note that you may be tempted to do: atoi(&temp) but this would not work, as &temp doesn't point to a null-terminated string.
请注意,您可能很想这样做: atoi(&temp) 但这不起作用,因为 &temp 不指向以空字符结尾的字符串。
回答by paxdiablo
You can replace the whole sequence:
您可以替换整个序列:
char a[] = "4x^0";
int *b;
b = new int[10];
char temp = a[0];
int temp2 = temp - 0;
b[0] = temp2;
with the simpler:
用更简单的:
char a[] = "4x^0";
int b = new int[10];
b[0] = a[0] - '0';
No need at all to mess about with temporary variables. The reason you need to use '0'
instead of 0
is because the former is the character'0' which has a value of 48, rather than the value0.
根本不需要弄乱临时变量。您需要使用'0'
而不是的原因0
是因为前者是字符“0”,其值为 48,而不是值0。