1. 程式人生 > >weifu的qt學習之路

weifu的qt學習之路

1、寫入文字檔案

使用文字檔案輸出的步驟:

        1)包含標頭檔案fstream

        2)建立一個ofstream物件

        3)將該ofstream物件同一個檔案關聯起來。 關聯的方法:ofstream物件.open("文字檔名")

        4)就像使用cout那樣使用該ofstream物件。

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

int main(int argc, char *argv[])
{
    char automobile[50];
    int year;
    double a_price,b_price;

    ofstream outFile;
    outFile.open("weifu.txt");

    cout<<"Enter the make and model of automobile: ";
    cin.getline(automobile,50);
    cout<<"Enter the model year: ";
    cin>>year;
    cout<<"Enter the original asking price: ";
    cin>>a_price;
    b_price=0.913*a_price;

    //
    cout<<fixed;
    cout.precision(2);
    cout.setf(ios_base::showpoint);
    cout<<"Make and model: "<<automobile<<endl;
    cout<<"Year: "<<year<<endl;
    cout<<"Was asking $"<<a_price<<endl;
    cout<<"Now asking $"<<b_price<<endl;

    //
    outFile<<fixed;
    outFile.precision(2);
    outFile.setf(ios_base::showpoint);
    outFile<<"Make and model: "<<automobile<<endl;
    outFile<<"Year: "<<year<<endl;
    outFile<<"Was asking $"<<a_price<<endl;
    outFile<<"Now asking $"<<b_price<<endl;

    outFile.close();
    return 0;
}

outFile.open("weifu.txt");   //在執行檔案下會自動生成一個weifu.txt文字檔案。

使用outFile物件將想要儲存到文字檔案中的記憶體儲存到weifu.txt中。

開啟已有的檔案,以接收輸出時,預設將它的長度截短為0,因此原來的內容將丟失。

2、讀取文字檔案

使用文字檔案輸出的步驟:

        1)包含標頭檔案fstream

        2)建立一個ifstream物件

        3)將該ifstream物件同一個檔案關聯起來,然後開啟該檔案。 

        關聯的方法:

                            char filename[SIZE];

                            cin.getline(filename,SIZE);

                            ifstream物件.open(filename);

        4)就像使用cin那樣使用該ifstream物件。

#include <iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
const int SIZE=60;
int main(int argc, char *argv[])
{
    char filename[SIZE];
    ifstream inFile;

    cout<<"Enter name of data file: ";
    cin.getline(filename,SIZE);
    inFile.open(filename);

    if(!(inFile.is_open()))
    {
        cout<<"Could not open the file "<<filename<<endl;
        cout<<"Program terminating.\n";
        exit(EXIT_FAILURE);//如果檔案沒有被開啟,則inFile.is_open()返回false,函式exit()終止程式。
    }

    double value;
    double sum=0.0;
    int count=0;
    inFile>>value;
    while(inFile.good())
    {
        ++count;
        sum+=value;
        inFile>>value;
    }

    if(inFile.eof())
        cout<<"End of file reached.\n";
    else if(inFile.fail())
        cout<<"Input terminating by data mismatch.\n";
    else
        cout<<"Input terminating for unknown reason.\n";
    if(count==0)
        cout<<"No data processed.\n";
    else
    {
        cout<<"Items read: "<<count<<endl;
        cout<<"Sum: "<<sum<<endl;
        cout<<"Average: "<<sum/count<<endl;

    }
    inFile.close();
    return 0;
}

is_open():檢查檔案是否被開啟。

函式exit()的原型包含在標頭檔案cstdlib中定義的。

eof()函式只能判斷是否達到EOF。