四、字符串和格式化输入/输出
1.前导程序
// talkback.c -- 演示与用户交互
#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);
pritnf("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 %d bytes to store it.
包含新特性:
■数组储存字符串
■%s转换说明来 处理 字符串的 输入 和输出
■C预处理器把字符串常量DENSITY定义为62.4
■C函数 strlen()获取字符串的长度
2.字符串简介
2.1 char类型数组和null字符
2.2 使用字符串
/* praise1.c -- 使用不同类型的字符串 */
#include <stdio.h>
#define PRAISE "You are an extraordinary being."
int main(void)
{
char name[40];
printf("What's your name?");
scanf("%s, name");
printf("Hello, %s. %s\n", name, PRAISE);
return 0;
}
//What's your name? Angela Plains
//Hello, Angela. You are an extraordinary being.
■字符串和字符
2.3 strlen()函数
/* praise2.c */
// 如果编译器不识别%zd, 尝试换成%u 或%lu。
#include <stdio.h>
#include <string.h> /* 提供 strlen()函数的原型 */
#define PRAISE "You are an extraordinary being."
int main(void)
{
char name[40];
printf("What's your name?");
scanf("%s, name");
printf("Hello, %s. %s\n", name, PRAISE);
printf("Your name of %zd letters occupies %zd memory cells.\n",
strlen(name), sizeof name);
printf("The phrase of praise has %zd letters ",
strlen(PRAISE));
printf("and occupies %zd memory cell.\n", sizeof PRAISE);
return 0;
}
//What's your name? Serendipity Chance
//Hello, Serendipity. You are an extraordinary being.
//Your name of 11 letters occupies 40 memory cells.
//The phrase of praise has 31 letters and occupies 32 memory cell.