C语言中数值和字符串的相互转换

ecnelises posted @ 2010年9月23日 03:33 in 计算机 with tags C语言 字符串 sprintf , 5520 阅读

整数->字符串可以使用stdio.h中的sprintf函数,有的人可能会说到itoa,但其实itoa不是C标准库的函数,是微软自己添加的。

sprintf的原型是:

int sprintf ( char * str, const char * format, ... );

和printf用法相同。当然也可用于其它类型如double。

例:

char str[20];
int s = 1000000;
sprintf(str, "%d", s);

字符->整数同样使用的也是stdio.h中的sscanf函数,stdlib.h中也有atoi和strtol可以进行转换。

int sscanf ( const char * str, const char * format, ... );
int atoi ( const char * str );
long int strtol ( const char * nptr, char ** endptr, int base);

sscanf和atoi的用法都很简单。值得一提的是strtol这个函数。第一个参数是源字符串,第二个参数用于接收非法字符串的首地址,第三个参数是转换后的进制。

什么叫非法字符串的首地址呢?比如nptr的值是"1234f5eg",base是10,endptr在调用后的值就是"f5eg"。如果base是16,那么endptr的值就是"g"(f和e是16进制的合法字符,而在10进制中却不是)。可以看出非法字符的类型和base有关。由于要修改指针的值,所以需要用到二重指针。另外,开头和结尾的空格会被忽略,中间的空格会被视为非法字符。

例:

char buf[] = "12435 fawr22g"
char *stop;
printf("%d\n", (int)strtol(buf,&stop,10));
printf("%s\n",stop);

输出结果为

12435

 fawr22g

另外,给出一个atoi的实现(glibc里的atoi是直接用strtol实现的):

#include <string.h>
#include <ctype.h>

int atoi(const char *s)
{
    int sign = (s[0] == '-') ? -1 : 1;
    int i, j, res = 0;
    int b = 1;
    for (j = strlen(s) - 1; j > i; --j) {
        b *= 10;
    }
    for (i = isdigit(s[0]) ? 0 : 1; i < strlen(s); ++i) {
        res += (s[i] - '0') * b;
        b /= 10;
    }
    return res;
}

 

Avatar_small
JSC Result madrasah 说:
2022年8月28日 11:51

Bangladesh Education Board DPE has conducted the class 8th grade of Junior School Certificate Exam and Junior Dakhil Certificate Exam on 1st to 15th November 2022 at all centers in division wise under Ministry of Primary and Mass Education (MOPME), and the class 8th grade terminal examination tests are successfully conducted for all eligible JSC/JDC students for the academic year of 2022. JSC Result madrasah Board The Bangladesh government Minister of Secondary Education is going to announce the JSC Result 2022 in student wise for division students in education board wise, and the result documents will be submitted to the Prime Minister of the country after then the result with mark sheet will be announced to public to check the individual result.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter