99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

C++ 文件

2018-03-24 15:29 更新

學(xué)習(xí)C++ - C++文件

寫入文本文件

以下代碼從用戶收集信息,將輸出發(fā)送到顯示器,然后將相同的輸出發(fā)送到文件。


#include <iostream>
#include <fstream>                  // for file I/O
using namespace std;
int main()
{
    char automobile[50];
    int year;
    double a_price;

    ofstream outFile;               // create object for output
    outFile.open("test.txt");    // associate with a file

    cout << "Enter the make and model: ";
    cin.getline(automobile, 50);
    cout << "Enter the model year: ";
    cin >> year;
    cout << "Enter the price: ";
    cin >> a_price;

    // display information
    cout << fixed;
    cout.precision(2);
    cout.setf(ios_base::showpoint);
    cout << "Model: " << automobile << endl;
    cout << "Year: " << year << endl;
    cout << "$" << a_price << endl;

    //File
    outFile << fixed;
    outFile.precision(2);
    outFile.setf(ios_base::showpoint);
    outFile << "Model: " << automobile << endl;
    outFile << "Year: " << year << endl;
    outFile << "$" << a_price << endl;
    
    outFile.close();                // done with file
    return 0;
}

上面的代碼生成以下結(jié)果。


從文本文件讀取

下面的程序打開用戶指定的文件,從文件中讀取數(shù)字,并報(bào)告值的數(shù)量,它們的總和及其平均值。


#include <iostream>
#include <fstream>        
#include <cstdlib>        
using namespace std;
const int SIZE = 60;
int main()
{
    char filename[SIZE];
    ifstream inFile;        // object for handling file input

    cout << "Enter file name:";
    cin.getline(filename, SIZE);
    inFile.open(filename);  // associate inFile with a file
    if (!inFile.is_open())  // if failed to open file, error out
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating.\n";
        exit(EXIT_FAILURE);
    }
    double value;
    double sum = 0.0;
    int count = 0;          // number of items read

    inFile >> value;        // get first value
    while (inFile.good())   // while input good and not at EOF
    {
        ++count;            // one more item read
        sum += value;       
        inFile >> value;    // get next value
    }
    if (inFile.eof())
        cout << "End of file reached.\n";
    else if (inFile.fail())
        cout << "Input terminated by data mismatch.\n";
    else
        cout << "Input terminated 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();         // finished with the file
    return 0;
}

上面的代碼生成以下結(jié)果。



以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號