1 前导程序
// talkback.c -- 演示与用户交互
#include <stdio.h>
#include <string.h> // 提供strlen()函数原型
#define DENSITY 62.4 // 人体密度(单位:磅/立方英尺)
int main(void)
{
float weight, volume;
int size, letters;
char name[40]; // name是一个可容纳40个字符的数组
printf("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;
}
程序的运行结果如下
ding@ding-ubuntu:~/primer$ ./a.out
What's your first name?
dingding
dingding, what's your weight in pounds?
125
Well, dingding, your volume is 2.00 cubic feet.
Also, your first name has 8 letters.
and we have 40 bytes to store it.
程序包含的特性
2 字符串简介
1 转义字符
注意,\0 是一个转义字符,ASCII码值为0,意为NULL 空字符,\0 用在字符串结尾处。
2 字符串简介
3 字符串的输入输出
/* 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;
}
程序执行结果:
ding@ding-ubuntu:~/primer$ ./a.out
What's your name? Angela Plains
Hello, Angela. You are an extraordinary being.
可以看到,scanf() 只读取了第一个单词,后面的字符串被忽略。实际上,scanf() 在遇到第一个空格,制表符 \t,或换行符 \n时就不再读取输入。也就是说,scanf() 只会读取第一个单词,而不是一整句。
扫描二维码关注公众号,回复:
9253629 查看本文章
4 strlen() 函数