从文本中读取一行、读取一个单词并输出

1. 给出两个文本文件:

file1:

中国 china
你好 hello
file2:

中国 china
你好 hello

2. 从文本file1中读取每行并输出;或者 从文本file2中读取每个单词并输出。

3.代码如下:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{

	//read contents from txt into a fstream object "inFile1".
	fstream inFile1("file1.txt");

	//情况1:读取文本中每一行内容,并输出.
	string line;
	//read every line in "inFile" and putout them.
	while(getline(inFile1,line))
		//process(line);
		cout << line << endl;	

	//read contents from txt into a fstream object "inFile2".
	fstream inFile2("file2.txt");
	//情况2:读取文本中每一单词内容,并输出.
	string word;
	//read every word in "inFile" and putout them.
	while(inFile2 >> word)
		//process(word);
		cout << word << ",";

	return 0;
}

4.运行结果如下:



5. 读取文本中每一单词内容,并输出到文本文件.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
	
	//read contents from txt into a fstream object "inFile".
	fstream inFile("file.txt");

	ofstream outFile("result.txt");
	
	string word;
	//read every word in "inFile" and put out them.
	while(inFile >> word)
		//process(word);
		outFile << word << " ";//使用空格隔开每个单词.
	
	return 0;
}


你可能感兴趣的:(从文本中读取一行、读取一个单词并输出)