C语言从stdin读取一行字符串的几种方法
2016-07-07 17:22
519 查看
C语言从stdin读取一行字符串的几种方法
gets
gets函数的头文件是<stdio.h>,原型如下:
char *gets(char *s);
gets从stdin中读入一行内容到s指定的buffer中,当遇到换行符或EOF时读取结束。读取成功时,返回s地址;失败时返回null。需要注意的是,gets会将行末尾的'\n'字符或EOF替换成'\0',这样,gets读取的内容中不包括'\n'字符。如果要获取读取字符串的长度,可以调用strlen函数获得。
[cpp] view
plain copy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int size = 1024;
char* buff = (char*)malloc(size);
// read lines
while(NULL != gets(buff)){
printf("Read line with len: %d\n", strlen(buff));
printf("%s", buff);
}
// free buff
free(buff);
}
fgets
fgets函数的头文件是<stdio.h>,原型如下:
char *fgets(char *s, int size, FILE*stream);
fgets从stream中读取最多size-1大小的内容到s指定的buffer中,当遇到换行符或EOF时读取结束。读取成功时,返回s地址;失败时返回null。需要注意的是,fgets会在所读取的内容后面添加'\0',这样,fgets读取的内容中会包括行末尾的'\n'字符。如果要获取读取字符串的长度,可以调用strlen函数获得。
[cpp] view
plain copy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int size = 1024;
char* buff = (char*)malloc(size);
// read lines
while(NULL != fgets(buff, size, stdin)){
printf("Read line with len: %d\n", strlen(buff));
printf("%s", buff);
}
// free buff
free(buff);
}
getline
getline函数的头文件是<stdio.h>,原型如下:
ssize_t getline(char **lineptr,size_t *n, FILE *stream);
getline从stream中读取一行内容到*lineptr所指定的buffer中,当遇到换行符或EOF时读取结束。*n是*lineptr所指定的buffer的大小,如果*n小于读入的内容长度,getline会自动扩展buffer长度,并更新*lineptr和*n的值。读取成功时,返回读入的字符个数;失败时返回-1。需要注意的是,gelines读取的内容中会包括行末尾的'\n'字符。
[cpp] view
plain copy
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, stdin)) != -1) {
printf("Retrieved line of length %zu, %u :\n", read, len);
printf("%s", line);
}
free(line);
exit(EXIT_SUCCESS);
}
自己实现my_getline
可以自己实现,原型如下:
int my_getline(char* line, intmax_size);
my_getline从stdin中读取最多max_size-1个字符到line所指定的buff中,当遇到换行符或EOF时读取结束。读取成功时,返回读取的字符串长度;失败时返回0。my_getline读取的内容中会包括行末尾的'\n'字符。
[cpp] view
plain copy
#include <stdio.h>
#include <stdlib.h>
int my_getline(char* line, int max_size)
{
int c;
int len = 0;
while( (c = getchar()) != EOF && len < max_size ){
line[len++] = c;
if('\n' == c)
break;
}
line[len] = '\0';
return len;
}
int main()
{
int max_size = 1024;
char* buff = (char*)malloc( sizeof(char) * max_size );
//getline
int len;
while(0 != (len = my_getline(buff, max_size))){
printf("Read line with len: %d\n", len);
printf("%s", buff);
}
free(buff);
}
相关文章推荐
- g++默认支持c++11标准的办法
- 泛化之美--C++11可变模版参数的妙用
- 简单的C语言小题目隐藏的知识(一)
- VC++6.0调试
- 循环双端队列示例C++_通话列表的保存
- C++ 几个不常用的关键字
- C++设计模式-Composite组合模式
- [note] C语言控制终端,缘何使用“\033[m”
- C++基础8【难】 回顾:数组指针,函数指针,函数指针做函数参数 C语言多态
- java 层调用Jni(Ndk) 持久化c c++ 对象
- POJ1001(C++处理大数)
- 设计模式(14)-Flyweight Pattern
- C++类构造函数,拷贝构造函数,赋值函数,析构函数几点注意
- c++——const
- 开始学习算法导论
- 数组引用:C++ 数组做参数 深入分析
- C++继承与派生
- 【c++程序】指针数组与数组指针
- c++——static关键字
- MFC使用ADO链接ACCESS的环境部署与注意事项