简体   繁体   English

将字符转换为C中的int

[英]Convert a char to an int in C

I want to make a program which converts 3www2as3com0 to www.as.com but I have got trouble at the beginning; 我想制作一个将3www2as3com0转换为www.as.com的程序,但是一开始我遇到了麻烦。 I want to convert the first number of the string (the character 3) to an integer to use functions like strncpy or strchr so when I print the int converted the program shows 51 instead of 3. What is the problem? 我想将字符串的第一个数字(字符3)转换为整数,以使用诸如strncpystrchr类的函数,因此当我打印转换为int的程序时,程序显示51而不是3。这是什么问题?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv) {

    /* argv[1]--->3www2as3com0*/

    char *string;
    char *p;  

    string=argv[1];
    p=string;

    char cond,cond2;

    cond=*p; //I want to have in cond the number 3

    cond2=(int)cond; //I want to convert cond (a char) to cond2(an int)

    printf("%d",cond2); //It print me 51 instead of 3

    return (EXIT_SUCCESS);
}

Your computer evidently encodes strings in a scheme called ASCII . 您的计算机显然以一种称为ASCII的方案编码字符串。 (I am fairly sure most modern computers use ASCII or a superset such as UTF-8 for char* strings). (我可以肯定,大多数现代计算机都将ASCII或超集(例如UTF-8)用于char*字符串)。

Notice how both printable and nonprintable characters are encoded as numbers. 请注意,可打印字符和不可打印字符都被编码为数字。 51 is the number for the character '3'. 51是字符“ 3”的数字。

One of the nice features of ASCII is that all the digits have increasing codes starting from '0'. ASCII的一个不错的功能之一是所有数字的编码都从“ 0”开始递增。

This allows one to get the numerical value of a digit by calculating aDigitCharacter - '0' . 这样就可以通过计算aDigitCharacter - '0'来获得数字的数值。

For example: cond2 = cond - '0'; 例如: cond2 = cond - '0';

EDIT: 编辑:

You should also probably also double check that the character is indeed a digit by making sure it lies between '0' and '9' ; 您还应该通过确保字符在'0''9'之间来仔细检查字符是否确实是数字;

If you want to convert a string containing more than one digit to a number you might want to use atoi . 如果要将包含多个位数的字符串转换为数字,则可能需要使用atoi It can be found in <stdlib.h> . 可以在<stdlib.h>找到它。

The character's integer value is the ASCII code for the digit, not the number it actually represents. 字符的整数值是数字的ASCII码,而不是它实际代表的数字。 You can convert by subtracting '0' . 您可以通过减去'0'来进行转换。

if( c >= '0' && c <= '9' ) val = c - '0';

Seems like the strings you are using will never have negative number, so you can use atoi(), returns the integer value from char. 似乎您正在使用的字符串永远不会有负数,因此您可以使用atoi(),从char返回整数值。 If it encounters something that is not a number, it will get the number that builds up until then. 如果遇到的东西不是数字,它将得到直到此为止积累的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM