1. 程式人生 > >C++引入外部txt檔案內容的方法

C++引入外部txt檔案內容的方法

1.引入標頭檔案fstream

2.定義物件如果是讀入應該用 ifstream類魔板,如果是往裡面寫應為ofream;int  out

3.例項化出來一個ifstream 的物件,物件.open(“”,)第一個引數寫檔案開啟的位置,第二個寫開啟的方式例如讀入用ios::in//int out stream

4.宣告一個字元指標陣列,陣列中存每一行的裁剪的每一個字串

5.宣告一個字元陣列用來存每一行的字串內容,注意:記憶體應該足夠大

6.!物件.eof()函式只要檔案沒有讀取結束,返回布林值 //end of file

7.物件.is_open()返回一個布林值,用來判斷檔案是否開啟成功。

8.物件.getline()函式得到每一行的內容

9.在使用strtok字串裁剪函式,詳情參見字串函式strtok的用法

10.最後物件.close()關閉檔案讀取。

11.程式碼如下:

#include <iostream>

#include<fstream>

#include<string>

using namespace std;


//讀取外部檔案(資料外部化:txt文件/xml檔案)


void main()
{
//----------C++讀取外部txt檔案內容的方法-------------
ifstream ReadFile;// in  file  stream 檔案輸入流類物件
ReadFile.open("data.txt",ios::in);//開啟檔案,開啟哪個檔案,開啟方式 in out stream


int id = 0 ; // 物品的ID
string name = "";// 物品的名字
int BuyPrice = 0;// 物品的買入價格
int SellPrice = 0;// 物品的賣出價格
int attribute = 0;// 物品的屬性


char * pStr[5] = {};//字元指標陣列 用來存入每行的n個字串


if( ReadFile.is_open() )//判斷檔案開啟是否成功
{
cout<<"檔案成功開啟......"<<endl;
char Content[256] = {};//用來儲存從檔案中讀取到的資料  整行的內容
while ( !ReadFile.eof() ) //只要檔案沒有讀取結束  end of file
{
ReadFile.getline(Content, 256);//獲取每行的內容,儲存位置,資料個數


int index = 0 ;//指標陣列的下標


/*
strtok:裁剪字串:將引數字串以" "分割
*/
char * pTemp = strtok(Content," ");//第一次進來就是第一個字串
while(pTemp)
{
pStr[index] = pTemp;
pTemp = strtok(NULL," ");
++index;
}
 
//----------轉換字串成為資料-----------
id = atoi(pStr[0]);// ascii to int
name = pStr[1];
BuyPrice  = atoi(pStr[2]);
SellPrice = atoi(pStr[3]);
attribute = atoi(pStr[4]);

//----------根據ID號判斷道具的型別-----------
cout<<id<<endl;
cout<<name.c_str()<<endl;
cout<<BuyPrice <<endl;
cout<<SellPrice<<endl;
cout<<attribute<<endl;
}
}
else
cout<<"檔案開啟失敗"<<endl;



ReadFile.close();




system("pause");
}