C语言笔记1--字符

写几个关于字符的知识点作为我的博客起点
1.

#include<stdio.h>
#include<stdlib.h>
void main()
{
    char ch='a';
    wchar_t wch='我';//宽字符的定义,占2字节
    printf("%d,%d,%d\n",sizeof(ch),sizeof('a'),sizeof(wch));
    system("pause");
}

这是初学者比较容易出错的地方,ch是char定义的字符变量,占1个字节,’a’是字符常量,为了兼容宽字符和窄字符,占4字节(1个空字符)。
2.

#include<stdio.h>
#include<stdlib.h>
void main()
{
    char ch1='0';
    char ch2='\0';
    int num=0;
    pritnf("%d\n",ch1);
    printf("%d\n",ch2);
    printf("%d\n",num);
    system("pause");
}

同时用整型格式输出,char类型打印了对应的ASCII码,int类型直接输出值
3.

#include<stdio.h>
#include<stdlib.h>
void main()
{
    char ch1='0';
    char ch2='\0';
    int num=0;
    char ch3=0;//和ch2等价
    pritnf("%d\n",ch1);
    printf("%d\n",ch2);
    printf("%d\n",num);
    printf("%d\n",ch3);
    printf("%c\n",ch3);
    system("pause");
}

ch3分别采用整型、字符格式输出,由结果可得,ch3与ch2等价的,都为空字符。
4.sprintf函数

#include<stdio.h>
#include<stdlib.h>
void main()
{
    char ch='i';
    char str[20];
    sprintf(str,"%c love C \n",ch);
    printf(str);
    system("pause");
}

sprintf()函数把第二个参数映射到第一个参数,第二个参数支持后面参数的格式输入。

    char ch='i';
    char str[20];
    int num=20;
    sprintf(str,"%c love %d \n",ch,num);//支持多个参数
    printf(str);
    system("pause");

猜你喜欢

转载自blog.csdn.net/weixin_40850689/article/details/81808956