C/C++ 读入一行字符串
2016-04-03 12:12
351 查看
C/C++ 读入一行字符串
标签(空格分隔): 常用代码积累1.gets
gets函数的头文件是#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); }
2. fgets
fgets函数的头文件是#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); }
**需要注意的是fgets保留换行符’\n’,而gets是从stdin输入,在读取字符串时会删除结尾的换行符’\n’;
同样,fputs写入时不包括换行符,而puts在写入字符串时会在末尾添加一个换行符。**
3. getline
对于C++语言,如果使用C字符串的话,就采用cin.getline()函数,如果采用string型字符串的话,就采用全局函数getline(cin,n);注意,这两个函数都不读入最后的换行符。
#include<string> #include<iostream> using namespace std; int main( ) { string s; char str[256]; getline(cin, s); cin.getline(str, sizeof(str)); return 0; }
参考:/article/4753538.html
非常值得看的博客:
/content/3670886.html
相关文章推荐
- win7 64下VC++6.0(Unable to register this add-in because its DLLRegisterServer return an error)
- C++笔记
- [leetcode]36. Valid Sudoku c语言
- 1123: 【C语言训练】列出最简真分数序列*
- c语言下的通用数据库接口(之sqlite消化,模拟c#,java的反射)
- 折半查找
- 顺序方法查找
- 图的遍历和二维矩阵动态分配内存
- 图的矩阵与邻接矩阵转换和遍历
- 图的邻接表存储
- 二叉树
- 队列
- C++智能指针
- 链栈
- 顺序栈
- 入栈问题
- 队列
- 数学表达式配对栈
- 链表设置
- C语言中如何解决重复include的问题