getline()的定义及应用
来源:互联网 发布:c 接ctp的源码示例 编辑:程序博客网 时间:2024/05/15 06:09
getline的两种定义
参考http://blog.csdn.net/yelbosh/article/details/7483521
1.全局函数,在头文件#include<string>
中,函数声明为:
- istream& getline ( istream& is, string& str, char delim )
- istream& getline ( istream& is, string& str )
2. istream的成员函数,函数声明为:
- istream& getline (char* s, streamsize n )
- istream& getline (char* s, streamsize n, char delim )
常用的是全局函数这种情况,getline函数的基本功能是将流istream& is
中的字符串存到string& str
当中去。
- 全局函数中两种声明的区别是第一种加了一个限定符号
char delim
,默认的限定符号为‘\n’,也即读到一个换行符就终止继续读取。 - istream的getline是在全局函数的getline函数的基础上,又多了一个终止读取的条件,即根据已读取的字符的个数来判定,实际上是读取n-1个字符,因为最后要为‘\0’留下一个位置。其他地方二者基本相同。
- 判断空行的办法是
str.length()==0
- 判断输入结束的办法是
is.eof()
C++依次读取文件中的字符串——getline()函数的应用
转自http://blog.csdn.net/sibo626/article/details/6781036
例如文件test.txt中有这么一段话:I am a boy. You are a girl.
如何一次一个的读取单词,即第一次读取I,第二次读取am,依次类推。
方法1:
#include <fstream> #include <string> #include <iostream> using namespace std; int main() { ifstream ifs("test.txt"); // 改成你要打开的文件 streambuf* old_buffer = cin.rdbuf(ifs.rdbuf()); string read; while(cin >> read) // 逐词读取方法一 cout << read; cin.rdbuf(old_buffer); // 修复buffer }
方法2:
#include <iostream> #include <fstream> using namespace std; int main() { ifstream ifs("test.txt"); // 改成你要打开的文件 ifs.unsetf(ios_base::skipws); char c; while(ifs.get(c)) // 逐词读取方法二 { if(c == ' ') continue; else cout.put(c); } }
方法3:
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream ifs("test.txt"); // 改成你要打开的文件 string read; while(getline(ifs, read, ' ')) // 逐词读取方法三 { cout << read << endl; } }
方法4:
#include <fstream> #include <iostream> using namespace std; int main() { ifstream ifs("test.txt"); // 改成你要打开的文件 char buffer[256]; while(ifs.getline(buffer, 256, ' ')) // 逐词读取方法四 { cout << buffer; } }
阅读全文
0 0
- getline()的定义及应用
- getline的应用
- getline的应用
- hdu1048及cin.getline,getline的用法
- 函数的定义及应用
- XML的定义及应用
- 常量的定义及应用
- 变量的定义及应用
- getline应用
- 指数分布的定义形式及应用
- 图像梯度的定义及应用
- 类的声明、定义及应用
- 函数的重载定义及应用
- 二维数组的声明,定义及应用
- 栈的定义及应用场景
- 微波的定义、性质及应用原理
- string类中getline函数的应用
- SOM_PAK源码编译出现getline重定义问题的解决
- jn-观展聆听合并,学艺术合并
- flex布局2
- 关于用delete方法删除不掉文件
- C++学习-模板
- IT 行业加班,到底有没有价值?
- getline()的定义及应用
- redis sorted set跳跃表的实现
- 【LeetCode】283. Move Zeroes
- guava的String之Splitter
- 线性表
- G
- Java值传递和引用传递
- 关于Android studio 模拟器打不开,而且连不上第三方模拟器,一直停留在waiting for target deviceto come online
- 九度oj 专题整理(模拟部分4)