假设文件内容为

1. hello1 hello2 hello3 hello4
2. dsfjdosi
3. skfskj ksdfls

输出每个单词

代码

#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string> using namespace std; int main()
{
string word;
ifstream infile("text");
if(!infile)
{
cout << "cannot open the file" << endl;
return ;
}
while(infile >> word)
cout << "word:" << word << endl;
infile.close();
}

结果

【c++】输出文件的每个单词、行-LMLPHP

分析

定义文件流infile,并绑定文件“text”,之后判定,如果打开错误,则提示错误,结束程序。否则,继续执行程序:

输入文件流infile把文件中的内容全部读入缓冲区(文件结尾符时停止往输入缓冲区内存),通过重定向符>>传到word(间隔福为Tab, Space, Enter)

输出每一行

代码

#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string> int main()
{
ifstream infile;
string line;
infile.open("text");
if(!infile)
cout << "error: cannot open file" << endl;
while(getline(infile, line))
{
cout << "line:" << line << endl;
}
infile.close();
}

结果

【c++】输出文件的每个单词、行-LMLPHP

分析

函数原型:istream& getline ( istream &is , string &str , char delim );

is为输入流, str为存储读入内容的字符串(不存储分割符), delim为终结符(不写默认为'\n')

返回值与参数is一样

同时输出每行和该行的每一个单词

代码

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>
using namespace std; int main()
{
ifstream infile;
string line, word;
infile.open("text");
if(!infile)
cout << "error: cannot open file" << endl;
while(getline(infile, line))
{
cout << "line:" << line << endl;
istringstream instream(line);
while(instream >> word)
cout << "word:" << word << endl;
cout << endl;
}
infile.close();
}

结果

【c++】输出文件的每个单词、行-LMLPHP

分析

<<是类istream 定义的,istringstream, ifstream 是其子类,都可以用

>>是类ostream 定义的,ostringstream, ofstream 是其子类,都可以用

用读出的每行初始化字符串流,在输出赋给单词(依旧分隔符隔开,但没有分隔符的事儿)

05-15 07:58
查看更多