加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

c++从文件读取一个单词

(2012-10-18 16:47:50)
标签:

杂谈

分类: c

在做一道练习时,遇到一个问题,首先是从文件中读取一行数据,存入vector中,这个使用getline很容易就实现了,附上代码。

#include

#include

#include

#include

#include

#include

using namespace std;

 

int main( void )

{

string filename;

cout << "please input your filename: " << filename << endl;

cin >> filename;

 

ifstream input( filename.c_str() );

while( !input ) {

cout << "filename is worong! " << endl;

cout << "please input again! " << endl;

cin >> filename;

}

 

vector str;

while( !input.eof() ) {

string line,;

getline( input, line );

str.push_back( line );

cout << endl;

}

return 0;

}


然后题目又要求从文件中以单词为单位读入到vector中,于是我上网搜了一下,答案五花八门,有什么strtok字符串分割函数,还有什么fscanf格式化输出函数,后来在看c++primer的时候发现一种很好用的方法,只要定义一个输入流的对象(ifstearm或者istringstream),再定义一个string对象就可以读取单词,附上代码:

#include

#include

#include

#include

#include

#include

using namespace std;

 

int main( void )

{

string filename;

cout << "please input your filename: " << filename << endl;

cin >> filename;

 

ifstream input( filename.c_str() );

while( !input ) {

cout << "filename is worong! " << endl;

cout << "please input again! " << endl;

cin >> filename;

}

 

vector str;

while( !input.eof() ) {

string line, word;

getline( input, line );

istringstream is( line );

str.push_back( line );

while( is >> word )

cout << " word is: " << word;

cout << endl;

}

 

return 0;

}


这是上面代码的改进版,首先将ifstream流和文件绑定,读取一行输入到line中,然后将istringstream流和line绑定,然后输入到word中即可。

也可以直接从ifstream输出word,结果也会是以一个单词的形式读取,大家可以自己尝试一下。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有