字符串操作函数
1、gets
从键盘获取一个字符串, 返回字符串的首地址。 可以获取带有 空格的字符串。
char *gets(char *s);
参数:用来存储字符串的空间地址。
返回值:返回实际获取到的字符串首地址。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
//gets
int main()
{
char str[10];
printf("获取的字符串为:%s", gets(str));
system("pause");
return EXIT_SUCCESS;
}
(其中第一行为手动输入)
(scanf也可以实现相同的功能,从屏幕中获取字符串,但是scanf的格式为scanf("%s", str))
2、fgets
fgets: 从stdin获取一个字符串, 预留 \0 的存储空间。空间足够读 \n, 空间不足舍弃 \n
char *fgets(char *s, int size, FILE *stream);
参1:用来存储字符串的空间地址。
参2:描述空间的大小。
参3:读取字符串的位置。 键盘 --》 标准输入:stdin
返回值:返回实际获取到的字符串首地址。
int main()
{
char str[10];
printf("获取的字符串为:%s", fgets(str, sizeof(str), stdin));
system("pause");
return EXIT_SUCCESS;
}
(从结果中可以看出他是自动留了一个 ‘/0’ 的位置)
3、puts
puts:将一个字符串写出到屏幕.
printf("%s", “hello”); / printf(“hello\n”); / puts(“hello”);
输出字符串后会自动添加 \n 换行符。
int puts(const char *s);
参1:待写出到屏幕的字符串。
返回值: 成功:非负数 0。 失败: -1.
int main()
{
char str[] = "hello world";
int ret = puts(str); // puts("hello world");
printf("ret = %d\n", ret);
system("pause");
return EXIT_SUCCESS;
}
(从结果中可以看出,输出字符串之后会自动换行,返回值也是0)
4、fputs
fputs:将一个字符串写出到stdout.输出字符串后, 不添加 \n 换行符。
int fputs(const char * str, FILE * stream);
参1:待写出到屏幕的字符串。
参数:写出位置 stdout(屏幕 --》标准输出: stdout)
返回值: 成功:0。 失败: -1.
//fputs
int main()
{
int ret = fputs("hello world\n", stdout);
printf("ret = %d\n", ret);
system("pause");
return EXIT_SUCCESS;
}