C++ Primer Plus 代码学习解析(第六章 6.13-6.16)

6.13 cinfish.cpp

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
const int Max = 5;
int main()
{
    using namespace std;
    // get data
    double fish[Max];
    cout << "Please enter the weights of your fish.\n";
    cout << "You may enter up to " << Max
        << " fish <q to terminate>.\n";
    cout << "fish #1: ";
    int i = 0;
    while (i < Max && cin >> fish[i]) {
        if (++i < Max)
            cout << "fish #" << i + 1 << ": ";
    }
    // calculate average
    double total = 0.0;
    for (int j = 0; j < i; j++)
        total += fish[j];
    // report results
    if (i == 0)
        cout << "No fish\n";
    else
        cout << total / i << " = average weight of "
        << i << " fish\n";
    cout << "Done.\n";
    // code to keep VC execution window open if q is entered
    //	if (!cin)  // input terminated by non-numeric response
    //	{
    //	    cin.clear();  // reset input
    //	    cin.get();    // read q
    //	}
    //	cin.get();    // read end of line after last input
    //	cin.get();    // wait for user to press <Enter>
    return 0;
}
  1. 该代码演示了将一系列数字输入到数组的过程
  2. while (i < Max && cin >> fish[i])首先判断&&左边的条件是否符合,避免溢出,不溢出则开始右侧表达式,将输入存到fish【】中
  3. 之后for循环计算总重量
  4. 最后还有if-else来判断输入是否为0,非零则正常计算(输入字母也可以看作0)

6.14 cingolf.cpp

#include <iostream>
const int Max = 5;
int main()
{
    using namespace std;
// get data
    int golf[Max];
    cout << "Please enter your golf scores.\n";
    cout << "You must enter " << Max << " rounds.\n";
    int i;
    for (i = 0; i < Max; i++)
    {
        cout << "round #" << i+1 << ": ";
        while (!(cin >> golf[i])) {
            cin.clear();     // reset input
            while (cin.get() != '\n')
                continue;    // get rid of bad input
            cout << "Please enter a number: ";
        }
    }
// calculate average
    double total = 0.0;
    for (i = 0; i < Max; i++)
        total += golf[i];
// report results
    cout << total / Max << " = average score "
            << Max << " rounds\n";
    // cin.get();
    // cin.get();
    return 0; 
}
  1. 该代码与上述代码实现功能相同,但对输入做了一些改良
  2. 首先是for循环for (i = 0; i < Max; i++)确保输入的值够到max
  3. 首先是while (!(cin >> golf[i]))条件来确保输入为数字,若为数字cin >> golf[i]为true,跳出循环,若不为数字,则cin >> golf[i]为false,进入循环,执行cin.clear(),重置输入

6.15 outfile.cpp

// outfile.cpp -- writing to a file
#include <iostream>
#include <fstream>                  // for file I/O

int main()
{
    using namespace std;

    char automobile[50];
    int year;
    double a_price;
    double d_price;

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

    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;
    d_price = 0.913 * a_price;

// display information on screen with cout

    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 $" << d_price << endl;

// now do exact same things using outFile instead of cout

    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 $" << d_price << endl;
    
    outFile.close();                // done with file
    // cin.get();
    // cin.get();
    return 0;
}
  1. 该程序演示了简单的文件输入,将输入的信息显示到屏幕上并写入到文件中
  2. 其中头文件fstream定义了一个用来处理输出的ofstream
  3. 其中ofstream outFile用来声明一个ofstream对象,outFile.open("carinfo.txt")用来将刚刚声明的对象与文件关联起来
  4. 防止数字太大,系统会以科学表示法的方式打印,所以使用一个流操作符 fixed,它表示浮点输出应该以固定点或小数点表示法显示
  5. cout.precision(val):在输出的时候,设定输出值以新的浮点数精度值显示,即小数点后保留val位
  6. cout.setf(ios::showpoint) 在c++中是为了保留原有的类型精度(四舍五入原则)

6.16 sumafile.cpp

// sumafile.cpp -- functions with an array argument
#include <iostream>
#include <fstream>          // file I/O support
#include <cstdlib>          // support for exit()
const int SIZE = 60;
int main()
{
    using namespace std;
    char filename[SIZE];
    ifstream inFile;        // object for handling file input

    cout << "Enter name of data file: ";
    cin.getline(filename, SIZE);
    inFile.open(filename);  // associate inFile with a file
    if (!inFile.is_open())  // failed to open file
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating.\n";
        // cin.get();    // keep window open
        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;       // calculate running total
        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
    // cin.get();
    return 0;
}
  1. 该代码用来读取文本文件
  2. 首先cin.getline(filename, SIZE)用来将输入的文件名储存到数组filename中,之后用作open()的参数inFile.open(filename);
  3. 读取前关键是要检查文件是否被打开 if (!inFile.is_open())
  4. 若正常读取,则进行这一循环while (inFile.good())
  5. 若不成功,则探究失败的原因是inFile.eof()(读取数据遇到eof)还是inFile.fail()(类型不匹配)
  6. 最后需要关闭文件inFile.close()

  • 13
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值