四、字符串和格式化输入/输出
4.printf() 和scanf()
4.5 使用scanf()
如果用scanf()读取基本变量类型的值,在变量名前加上一个&,如果用scanf()把字符串读入字符串数组中,不用使用&
// input.c -- 何时使用&
#include <stdioh>
int main(void)
{
int age; //变量
float assets; //变量
char pet[30]; //字符数组,用于储存字符串
printf("Enter your age, assets, and favorite pet.\n");
scanf("%d %f", &age, &pet);
scanf("%s", pet);
printf("%d $%.2f %s\n", age, assets, pet);
return 0;
}
//Enter your age, assets, and favorite pet.
//38
//92360.88 llama
//38 $92360.88 llama
\\\\\\\\\\\
三个表格
\\\\\\\\\\\\
#从scanf()角度看输入
#格式字符串中的普通字符
#scanf()的返回值
4.6 printf()和scanf()的*修饰符
/* varwid.c -- 使用变宽输出字段 */
#inlude <stdio.h>
int main(void)
{
unsigned width, precision;
int number = 256;
double weight = 242.5;
printf("Enter a field width:\n");
scanf("%d", &width);
printf("The number is :%*d:\n", width, number);
printf("Now enter a width and a precision:\n");
scanf("%d %d", &width, &precision);
printf("Weight = %*.*f\n", width, precision, weight);
printf("Done!\n");
return 0;
}
//Enter a field width:
//6
//The number is : 256:
//Now enter a width and a precison:
//8 3
//Weight = 242.500
//Done!
/* skiptwo.c -- 跳过输入中的前两个整数 */
#inlude <stdio.h>
int main(void)
{
int n;
print("Plese enter three integers:\n");
scanf("%*d %*d %*d", &n);
printf("The last interger was %d\n", n);
return 0;
}
//Please enter three integers:
//2013 2014 2015
//The last integer was 2015
4.7 printf()的用法提示
//对齐
printf("%9d %9d %9d\n", val1, val2, val3);