[英]How to manipulate char - C
In my program, I need the user to enter coordinates, starting with a letter and finishing by a number.在我的程序中,我需要用户输入坐标,以字母开头,以数字结尾。 The format is "e6", for example.
例如,格式为“e6”。 I want to write a function that converts the number into an int.
我想写一个 function 将数字转换为 int。 With this example, i want the "6" to be converted to int 6. My problem comes from the fact that the number can go up to 11.
在此示例中,我希望将“6”转换为 int 6。我的问题来自数字 go 最多 11 的事实。
I tried this function:我试过这个 function:
int function(char c[]) {
if (c[2]=='0') {
return (int)c[1] * 10;
}
else if (c[2]=='1') {
return (int)c[1]*10 + 1;
}
else {
return (int)(c[1]-'0');
}
}
The problem is that it returns numbers unrelated to the input, like "490" if I enter "f10".问题是它返回与输入无关的数字,例如如果我输入“f10”,则返回“490”。
I hope my problem is clear enough so you can help me !我希望我的问题足够清楚,所以你可以帮助我!
Answer: I understand now my error, and what -'0' means.回答:我现在明白我的错误了,-'0' 是什么意思。 The new working function is:
新的工作 function 是:
int function(char c[]) {
if (c[2]=='0') {
return (int)(c[1]-'0') * 10;
}
else if (c[2]=='1') {
return (int)(c[1]-'0')*10 + 1;
}
else {
return (int)(c[1]-'0');
}
}
Thanks to all of you !感谢大家 !
Here you convert a digit character to its value by subtracting '0'
:在这里,您通过减去
'0'
将数字字符转换为其值:
return (int)(c[1]-'0');
That's correct (although the cast is completely unnecessary).这是正确的(尽管演员阵容完全没有必要)。
But here you just use the digit character as though it were a value:但是在这里你只是使用数字字符,就好像它是一个值:
return (int)c[1] * 10;
Since '1'
is 49, the output is not surprising.由于
'1'
为 49,因此 output 也就不足为奇了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.