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

  • 函数 strlen()
  • 关键字 const
  • 字符串
  • 如何创建、存储字符串
  • 如何使用strlen()函数获取字符串的长度
  • 用C预处理器指令#define和ANSIC的const修饰符创建符号常量
#include <stdio.h> 
#include <string.h> //提供 strlen() 函数 的 原型 
#define DENSITY 62.4  //人体密度(单位:磅/立方英尺)

int main() 
{ 
    float weight,volume; 
    int size,letters; 
    char name[40]; //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; 
}


Hi! What's your first name? 
Christine
Christine, what's your weight in pounds? 
154 
Well, Christine, your volume is 2.47 cubic feet. 
Also, your first name has 9 letters, 
and we have 40 bytes to store it.

该程序包含以下特性。

  • 用数组(array)储存字符串。在该程序中,用户输入的名被储存在数组中,该数组占用内存中40个连续的字节,每个字节存储一个字符值。
  • 使用%s转换说明来处理字符串的输入和输出。注意、在scanf()中,name没有&前缀,而weight有(&weight和name都是地址)。
  • 用C预处理器把字符常量DENSITY定义为62.4
  • 用C函数strlen()获取字符串的长度。

char类型数组和null字符

C语言没有用于储存字符串的变量类型,字符串都被储存在char类型的数组中。数组由连续的存储单元组成,字符串中的字符被储存在相邻的存储单元中,每个单元储存一个字符。

字符串和字符

字符串常量”x”和字符常量’x’不同。

  • 区别之一在于’x’是基本类型(char),而”x”是派生类型(char数组);
  • 区别之二是”x”实际上由两个字符组成:’x’和空字符\0
- - -
‘x’是一个字符 x
“x”是一个字符串 x \0

strlen()函数

sizeof()包含空字符串所有存储单元的字符串长度
strlen()不包含空字符串所有存储单元的字符串长度

常量和C预处理器

定义常量PI的两种方式:

  • #define Pi 3.1415926f;
  • const float pi 3.1415926f;


    区别:

  • 第一种方式:是将Pi定义成一种符号,此时Pi只是3.1415926的别名,在编译期间用3.1415926去取代Pi的值;

  • 第二种方式:是将PI定义成变量,但告诉编译器它的值是固定不变的,如果在程序中试图去修改它的值,在编译时会报错;

指令 描述
#define 定义宏
#include 包含一个源代码文件
#undef 取消已定义的宏
#ifdef 如果宏已经定义,则返回真
#ifndef 如果宏没有定义,则返回真
#if 如果给定条件为真,则编译下面代码
#else #if 的替代方案
#elif 如果前面的 #if 给定条件不为真,当前条件为真,则编译下面代码
#endif 结束一个 #if……#else 条件编译块
#error 当遇到标准错误时,输出错误消息
#pragma 使用标准化方法,向编译器发布特殊的命令到编译器中




上一页  C Primer Plus阅读学习(二)

下一页  C Primer Plus阅读学习(四)