第四章总结

示例程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <string.h> //提供strlen();函数原型
#define DENSITY 62.4
int main() {
float weight , volume;
int size, letters;
char name[40]; //使用数组
printf("你好!你姓什么?\n");
scanf("%s",name) //数组不使用&
printf("%s,你体重是多少?\n",name);
scanf("%f",&weight);
size = sizeof name; //sizeof函数对于具体量括号是可选的
letters = strlen(name);
volume = weight/DENSITY;
printf("好的,%s,你的人体密度为%2.2f \n",name,volume);
printf("然后,你的姓有%d个字母\n",letters);
printf("你的名字占用 %d bytes的存储空间\n",size);
return 0;
}

解释程序

  1. <string.h> 提供 strlen() 函数
  2. define XXX volune C预处理器定义常量
  3. %s 字符串型格式符 处理字符串的输入和输出
  4. weight 使用 & 而name未使用
  5. strlen() 获取字符串长度

字符串概述

字符串

  • 一个或多个字符的序列
  • C没有为字符串定义专门的变量类型
  • 字符串存储在 char 数组中
  • 字符串存储空间要比存储的字符串的字符数多1

实例

字符串存储空间要比存储的字符串的字符数多1

scanf()函数特性

当遇到一个空白字符空格(blank),制表符(tab)或换行符(newline)处停止读取,若停止读取的字符串后还有字符串,则在下一次使用scanf()函数时接着读取

一般情况下,使用%s的scanf()只会吧一个单词作为字符串读入

字符和字符串

未完待续~