1. 程式人生 > >C++中string類及檔案流類(ofstream,ifstream)的基本操作---按行讀取文件

C++中string類及檔案流類(ofstream,ifstream)的基本操作---按行讀取文件

先說明一個問題:java構建物件只能使用new的方法,而C++則不然。

下面程式碼實現讀取test.txt檔案中的內容並顯示,同時將某一個字串輸入到檔案test1.txt中。

函式getline(ifstream& param1, string& param2);按行讀取文件,若處於檔案尾部,返回false。

函式object.c_str();將字串轉換成字元陣列,返回指標。

其它函式的使用請參照程式。

// test_max.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
	string filename;
	string filename1;
	filename="F:\\workspace\\JavaPrj\\test.txt";
	filename1="F:\\workspace\\JavaPrj\\test1.txt";
	ifstream infile(filename.c_str());
	ofstream outfile(filename1.c_str());

	string temp;

	temp="cjc is a student.";
	outfile.write(temp.c_str(), temp.length());
	outfile.close();
	int a=temp.find("is");
	cout<<a<<endl;

	while(getline(infile,temp))
	 {
			cout<<temp<<endl;
	 }
	cout << "Hello world!" << endl;
	system("pause");
    return 0;
}