您的位置:首页 > 其它

关于getline()的一片文章(zt)

2007-06-06 21:40 302 查看
怎样获得文本的每一行呢 标准库支持 getline()函数 声明如下
istream&
getline( istream &is, string str, char delimiter );
getline()读取 istream 对象 向 string 对象插入字符 包括空格 直到遇到分割符 文件
结束 或者被读入的字符序列等于 string 对象的 max_size()值 在该点处读入操作失败。
在每次调用 getline()之后 我们都会将 str 插入到代表文本的字符串 vector 中 下面是一
般化的实现17 我们已经将它提取到一个函数中 命名为 retrieve_text()

// 返回值是指向 string vector 的指针
vector<string,allocator>*
retrieve_text()
{
string file_name;
cout << "please enter file name: ";
cin >> file_name;
// 打开文本文件以便输入 ...
ifstream infile( file_name.c_str(), ios::in );
if ( ! infile ) {
cerr << "oops! unable to open file "
<< file_name << " -- bailing out!/n";
exit( -1 );
}
else cout << '/n';
vector<string, allocator> *lines_of_text =
new vector<string,allocator>;
string textline;
typedef pair<string::size_type, int> stats;
stats maxline;
int linenum = 0;
while ( getline( infile, textline, '/n' )) {
cout << "line read: " << textline << '/n';
if ( maxline.first << textline.size() ) {
maxline.first = textline.size();
maxline.second = linenum;
}
lines_of_text->push_back( textline );
linenum++;
}
return lines_of_text;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: