C Primer Plus 学习 第四章

字符串与格式化输入/输出

函数 strlen()

关键字 const

利用#define 和 const创建符号常量

#include <stdio.h>
#include <string.h>
#define DENSITY 62.4

int main()
{
    float weight,volume;
    int size,letters;
    char name[40];

    printf("hi , what's your first name \n");
    scanf("%s",name);
    printf("%s,what's your weight in pounds?\n",name);
    scanf("%f",&weight);
    size=sizeof name;
    letters=strlen(name);
    volume=weight/DENSITY;
    printf("well,%s,your volume is %2.2f cubic feet.\n",name,volume);
    printf("Also,your first name has %d letters,\n",letters);
    printf("and we have %d bytes to store it.\n",size);
    return 0;
}

字符串以字符数组的形式存在。字符数组的末尾以\0结尾,并占用一个字符空间。

scanf()  只会读取字符串中的一个单词,而不是一整句

字符串常量和字符常量的区别:

字符常量X  是基本类型 char   字符串常量是派生类型 char[]

字符串常量X 包含字符X和/0空字符。   而 字符常量X只包含X

sizeof 和 strlen()的区别

sizeof是计算空间的大小    比如  name[40]  就是40个大小,而不会管数据一共填充了多少

strlen()是计算数据占用空间的大小。未填充的空间,不会计算。空字符\0也不会占用strlen()的长度

猜你喜欢

转载自www.cnblogs.com/Lonelychampion/p/11851012.html