void test_string()
{
/*
1、声明字符串
数组word是常量;
指针wd是变量;
所以,只有指针能进行递增操作!!!
*/
char word[] = "We are here today!";
char *wd = "Where are you now?";
int i = 0;
//数组遍历
while(*(word+i)!='\0')
{
putchar(*(word+i));
i++;
}
//指针遍历
while(*(wd)!='\0')
{
putchar(*(wd++));
}
/*
2、puts只用于输出字符串,并自带回车
*/
//puts(word);
//puts(wd);
}
void test_gets_puts()
{
/* 3、
gets():读取整行输入,直至遇到换行符,然后丢弃换行符,储存其余字符,
并在这些字符的末尾添加一个空字符使其成为一个字符串.
puts():显示字符串,并在末尾添加换行符
*/
char words[LEN];
puts("Enter a string:");
gets(words);
puts(words);
puts("Done!");
/*
Note:
gets()函数不安全,它只知道数组的首地址,不知道数组的长度,
如果输入的字符串过长,会导致缓冲区溢出(Buffer Overflow)。
*/
}
void test_fgets_fputs()
{
char words[LEN];
puts("Enter:");
fgets(words,LEN,stdin);//读入从键盘输入的数据,则以stdin(标准输入)作为参数
fputs(words,stdout);//显示在计算机显示器上,则以stdout(标准输出)作为参数
puts("Done!");
/* 4、
case 1:字符串不超长
输入:
I am ok
实际输入:I am ok\n 因为敲了回车,所以加\n;
word数组中保存:I am ok\n\0 因为要变成字符串,所以末尾加\0;
gets()会丢弃换行符,所以gets()的实际输入:I am ok
输出:
I am ok
Done!
case 2:字符串超长
输入:
I am your friend
实际输入:I am your friend\n
word数组中保存:I am your\0 因为fgets()一次最多读入LEN - 1个字符
输出:
I am yourDone!
fputs()不会自动添加换行符;
*/
}
/* 5、
空字符:'\0',整数类型,用数值0来表示;空字符是一个字符,占1字节;
空指针:NULL,指针类型,也用数值0来表示;空指针是一个地址,通常占4字节;
*/
void test_scanf()
{
/* 6、
scanf()更像是“获取单词”函数,而不是“获取字符串”函数;
scanf()返回一个整数值,该值等于scanf()成功读取的项数或EOF(读到文件结尾时返回EOF)。
*/
char name1[11], name2[11];
int count;
printf("Please enter 2 names.\n");
count = scanf("%5s %10s",name1,name2);
printf("I read the %d names %s and %s.\n",count,name1,name2);
}
字符串输入与输出
最新推荐文章于 2024-04-16 23:31:54 发布