读书共享 Primer Plus C-part 4

时间:2024-07-01 16:32:50

第四章 字符串和格式化输入输出

  • 关于printf

-  左对齐

#include<stdio.h>

void main()
{
char str [100] = "liuchuanwu";
printf("%20s\n",str);
printf("%-20s\n",str); }

  读书共享 Primer Plus C-part 4

  • 关于浮点数的打印
#include<stdio.h>
#include<string.h>
int main()
{
char str [] = "liuchuanwu";
short s1 = ;
short s2 =;
int i1= ;
long int l1= ;
long int l2=;
float f1 = 1234.6789;
printf("%d %d\n",sizeof(s1), s1);
printf("%d %d\n",sizeof(s2), s2);
printf("%d %d\n",sizeof(i1), i1);
printf("%d %ld\n",sizeof(l1), l1);
printf("%d %ld\n",sizeof(l2), l2);
printf("%20s\n",str);
printf("%-20s\n",str);
printf("%d \n %d\n",sizeof(str),strlen(str)); printf("%2.3f \n",f1);
printf("%0.3f \n",f1);
printf("%-10.3f \n",f1);
printf("%10.3f \n",f1);
return ; }

%x.y x小于浮点数本身的大小全部打印 x大于浮点数本身按照x长度打印。

x的长度 指整数长度+小数长度+1

读书共享 Primer Plus C-part 4

  • 关于字符串打印长度
#include<stdio.h>
#include<string.h>
int main()
{
char str [] = "liuchuanwu";
printf("%20.1s \n",str);
return ; }

对于%20.1s 20指的是整个打印占多大,.1指的是打印多少个真正的字符。

读书共享 Primer Plus C-part 4

  • 对于长字符串处理
#include<stdio.h>
#include<string.h>
int main()
{
char str [] = "liuchuanwu";
printf("%20.1s \n",str);
printf("liuchuanwu is a handman\n");
printf("liuchuanwu is a \
handman\n");
printf("liuchuanwu is a "
"handman\n"); return ; }

读书共享 Primer Plus C-part 4

  • 关于sizeof 和strlen
#include<stdio.h>
#include<string.h>
int main()
{
char str [100] = "liuchuanwu";
printf("%20s\n",str);
printf("%-20s\n",str);
printf("%d \n %d\n",sizeof(str),strlen(str));
return 0; }

  sizeof 所占字节大小 strlen到\0还有多久

读书共享 Primer Plus C-part 4

  • 关于scanf

scanf 的第二个输入参数是指针,所以针对基本类型需要使用&获取内存地址,对于字符串则不需要,字符串本身为指针。

#include<stdio.h>
#include<string.h>
int main()
{
char str [] = "liuchuanwu";
int age = ;
printf("input your name and age \n",str);
scanf("%s",str);
scanf("%d",&age);
printf("%d \n%s\n",age,str); return ; }

读书共享 Primer Plus C-part 4

残留问题针对空行如何处理