如何从文件读取并将数据存储到结构并计算公式?

时间:2018-10-19 05:32:32

标签: c++

我是C ++的新手。我有一个名为test.txt的文件,其中包含以下数据

2 Salman Khan 20 100000 4.75 1000 Aamir khan 30 200000 5.25 1000 哪里 第一行是用户记录的数量, 第二行是名称,以空格分隔,并且 第三行包括用户资格的年份,金额,费率,每月金额。

我想计算公式并显示在表格中。

到目前为止,我已经完成的工作如下:

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

struct Customers
{
    char first_name[50];
    char last_name[30];
    int years; 
    float amount; 
    float interest_rate;
    float amount_per_month;
}; 

int main() {
    Customers cus;

    int sum = 0;
    string x,line;
    string fileName = "";
    ifstream inFile;

    string firstLine;
    int numberOfCustomers = 0;

    cout << "Enter File Name: \n";
    cin >> fileName;
    cout << "Reading File : '"+ fileName+"'" << endl;

    inFile.open(fileName);
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }

    if (inFile.good())
      {
        getline(inFile, firstLine);
        numberOfCustomers = stoi(firstLine);
        cout << "Available Loan Applications : " << numberOfCustomers << endl;
      }

     while (inFile >> x) {
       cout << x << endl;
       cin >> cus.first_name;
    }

    inFile.close();
    return 0;
}

我正在尝试将数据存储到结构中,然后进行计算,我需要帮助将数据存储到结构中。

1 个答案:

答案 0 :(得分:3)

您可以使用流提取和流插入运算符来读取/写入自定义数据类型:

#include <cstddef>   // std::size_t
#include <cstdlib>   // EXIT_FAILURE
#include <iterator>  // std::istream_iterator<>
#include <vector>    // std::vector<>
#include <string>    // std::string
#include <fstream>   // std::ifstream
#include <iostream>  // std::cout, std::cerr, std::ostream, std::istream

using namespace std;

struct Customer {
    string first_name, last_name;
    int years;
    float amount, interest_rate, amount_per_month;
};

// define a stream extraction operator that takes a Customer on the right hand side
// usage examples: std::cin >> customer;
//                 file >> customer;
istream& operator>>(istream &is, Customer &customer)
{
    // don't write directly into the members of Customer to not leave
    // the object in a flunky state if extraction fails for some value.
    string first_name, last_name;
    int years;
    float amount, interest_rate, amount_per_month;

    if (!(is >> first_name >> last_name >> years >> amount >> interest_rate >> amount_per_month))
        return is;  // if extraction of a value fails end here

    // if we reach here all values have been read successfully and can be
    // assigned to the customer:
    customer = { first_name, last_name, years, amount, interest_rate, amount_per_month };
    return is;
}

// define a stream insertion operator that takes a Customer on the right hand side
// usage examples: std::cout << customer;
//                 file << customer;
ostream& operator<<(ostream &os, Customer const &customer)
{
    os << customer.first_name << ' ' << customer.last_name << '\n' << customer.years << ' ' 
       << customer.amount << ' ' << customer.interest_rate << ' ' << customer.amount_per_month;

    return os;
}

int main()
{
    cout << "Enter filename: ";
    string fileName;
    cin >> fileName;

    ifstream inFile{ fileName };  // define variables as close to where they're
                                  // used. Use the constructor where app-
                                  // ropriate - here to open the file.
    if (!inFile.is_open()) {      // if the file couldn't be opened
        cerr << "Unable to open \"" << fileName << "\" for reading!\n\n";
        return EXIT_FAILURE;      // exit main() returning a value that
    }                             // indicates an error

    cout << "Reading file \"" + fileName + "\":\n";

    size_t numCustomers;
    if (!(inFile >> numCustomers)) {  // read the number of customers before-
                                      // hand since this value is not part of
                                      // a customer record.
        cerr << "Couldn't read number of customers from \"" << fileName << "\"!\n\n";
        return EXIT_FAILURE;
    }

    // use an istream_iterator that will use our stream extraction operator
    // to read customers from inFile until it reaches EOF or an error occurs.
    vector<Customer> Customers{ istream_iterator<Customer>{ inFile },
                                istream_iterator<Customer>{} };

    if (numCustomers != Customers.size()) {  // check if the number of customers
                                             // specified in the file matches
                                             // the number of customers we
                                             // were able to extract.
        cerr << "Number of customers specified in \"" << fileName
             << "\" does not match the number of customers read!\n\n";
        return EXIT_FAILURE;  // if the numbers don't match there was an error
    }                         // while reading the records from the file

    for (auto const &c : Customers)  // just to check print the customers
        std::cout << c << '\n';
}

输出:

Enter File Name: test.txt
Reading file "test.txt":
Salman Khan
20 100000 4.75 1000
Aamir khan
30 200000 5.25 1000