1、字符串
字符串在C语言中只有常量没有对应的字符串类型,所以在存储时借助字符数组存储,即存储在一块连续的空间中。
"helloworld"
计算机在存储字符串时,会在后面自动加'\0'
1》计算字符串长度:
---》调用字符串函数:strlen
#include <stdio.h>
#include <string.h>
int main(void)
{
int len;
len = strlen("helloworld");
printf("len = %d\n",len);
return 0;
}
结果:len = 10,原因:字符串处理函数strlen计算的是字符串的实际长度
---》使用运算符:sizeof
#include <stdio.h>
#include <string.h>
int main(void)
{
int len;
len = sizeof("helloworld");
printf("len = %d\n",len);
return 0;
}
结果:len = 11,原因:sizeof计算的是该数据占用内存空间的长度
2》其他与字符串相关的函数:strcpy,strcat,strcmp
2、格式化IO
1》IO:in(输入),out(输出)
| | in (输入) |键盘、文件
| 程 | <-----------(外界) | buf缓存、网络
| 序 | ----------> (外界 | 屏幕、文件
| | out (输出) | buf缓存、网络
2》格式化:
按一定的格式输入或者输出,叫格式化输入或输出,一般输入输出都是通过调用IO函数实现的
3》格式化输出函数:
int printf(const char *format, ...); //向屏幕上输出
int a = 101;
float b = 23.45;
printf("a = %d, b = %f\n", a, b);
%d和%f为转换说明符,在输出时,会被后面的参数值替换
注意:
----》转换说明符的个数必须和变参的个数相等
----》转换说明符的类型必须和变参的类型匹配
----》输出float和double型数据时,都使用%f
----》变参可以是:变量,常量,表达式,指针(地址)
----》如果要打印%本身,则需要用%%代替。
----》转换说明符:
----》修饰符:
int fprintf(FILE *stream, const char *format, ...); //向文件里输出(写入)
int sprintf(char *str, const char *format, ...); //向str缓存(内存空间)输出(写入)
int snprintf(char *str, size_t size, const char *format, ...); //向str缓存(内存空间)输出(写入)
4》格式化输入函数:
int scanf(const char *format, ...); //从键盘输入
#include <stdio.h>
int main(void)
{
int a;
float b;
char ch;
scanf("%d %c %f",&a,&ch,&b);
//scanf("a=%d,b=%f",&a,&b);
printf("a = %d, b = %f\n",a,b);
printf("ch = %c\n",ch);
return 0;
}
注意:
----》转换说明符的个数必须和变参的个数相等
----》转换说明符的类型必须和变参的类型匹配
----》输入float数据必须用%f,输入double型数据必须用%lf
----》变参只能是地址量
scanf返回值:正确接收参数的个数,例如:
<pre name="code" class="cpp">#include <stdio.h>
int main(void)
{
printf("%-5d\n",123);
printf("%05d\n",123456);
printf("%d\n",-100);
printf("%+d\n",+100);
printf("%5.2f\n",1.2);
int a = 123;
short b = 100;
char c = 10;
long d = 123456;
long long e = 123456789;
printf("a = %d\n",a);
printf("b = %hd\n",b);
printf("c = %hhd\n",c);
printf("d = %ld\n",d);
printf("e = %lld\n",e);
return 0;
}
int fscanf(FILE *stream, const char *format, ...); //从文件中输入(获取数据)
int sscanf(const char *str, const char *format, ...); //从缓存(内存)中输入(获取数据)