c语言中char类型转int类型

前言

在九度oj做acm的时候,经常会遇到了char类型和int类型相互转化的问题,这里进行一下总结。今后,可能会多次更新博客,因为半年做了很多总结,但是都是保存在word文档上了,现在开始慢慢向CSDN博客转移。


问题类型


char型数字转换为int型

转换方法

a[i] - '0'

参考程序

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

int main()
{
	char str[10];
	int i, len;

	while(scanf("%s", str) != EOF)
	{
		for(i = 0, len = strlen(str); i < len; i++)
		{
			printf("%d", str[i] - '0');
		}
		printf("\n");
	}

	return 0;
}

int类型转化为char类型

转换方法

a[i] + '0'


参考程序

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

int main()
{
	int number, i;
	char str[10];

	while(scanf("%d", &number) != EOF)
	{
		memset(str, 0, sizeof(str));
	
		i = 0;
		while(number)
		{
			str[i ++] = number % 10 + '0';
			number /= 10;
		}		
		puts(str);		
	}

	return 0;
}


C语言中单引号和双引号的区别


1、含义不同

单引号引起的一个字符实际上代表一个整数,整数值对应于该字符在编译器采用的字符集中的序列值。而一般我们的编译器采用的都是ASCII字符集。因此's'的含义其实和十进制数115的含义是一致的。
而用双引号引起的字符串,代表的是一个指向无名数组起始字符的指针

2、大小不同

单引号引起的一个字符大小就是一个字节
而用双引号引起的字符串大小字符的总大小+1,因为用双引号引起的字符串会在字符串末尾添加一个二进制为0的字符'\0'。

posted @ 2011-12-15 21:15  java程序员填空  阅读(2668)  评论(0编辑  收藏  举报