【问题标题】:How to write in text file by line and column using C++如何使用 C++ 逐行逐列写入文本文件
【发布时间】:2017-09-18 21:14:24
【问题描述】:

你能检查一下我的代码有什么问题吗?我只想制作可以将信息存储在文本文件中并会显示在文本文件中的程序,如下所示:

BookID BookTitle AuthorName BookDepartment BookIssuer

但只有1本书才成功,如果我输入2本书,它将获得无穷大

#include<iostream>
#include<fstream>
#include<iomanip>

using namespace std;

void IssueBooks(){
    int SIZE;
    cout << "How many books you want to borrow?"<< endl;
    cin >> SIZE;

    string booksTitle[SIZE], department[SIZE], authorName[SIZE], 
    BooksIssuer[SIZE];
    double booksID[SIZE];

    for (int i = 0; i < SIZE; i++ ){
            for (int j = 0; j < SIZE; j++){
                cout << "Enter Book ID:" << endl;
                cin >> booksID[j];

                cout << "\nEnter Book Title:" << endl;
                cin >> booksTitle[j];

                cout << "\nEnter Book Author:" << endl;
                cin >> authorName[j];

                cout << "\nEnter Book Department:" << endl;
                cin >> department[j];

                cout << "\nEnter Book Issuer: " << endl;
                cin >> BooksIssuer[j];

                ofstream out("IssueRecord.txt");
                out << setw(10) << booksID[j];
                out << setw(10) << booksTitle[j];
                out << setw(10) << authorName[j];
                out << setw(10) << department[j];
                out << setw(10) << BooksIssuer[j];

            }
        }




}

int main(){
    IssueBooks();

return 0;
}

谢谢

【问题讨论】:

  • 我认为初学者不需要外部 for 循环
  • 无关:通过将所有变量设置为 IssueBooks 的本地变量,您很难将收集到的信息恢复到功能之外。
  • string booksTitle[SIZE] 和其他使用SIZE 大小的固定大小的数组被称为“可变长度数组”,这是一种非标准的扩展,只有少数编译器支持。请改用std::vector。实际上,在这个例子中,根本不需要使用任何数组。
  • @RemyLebeau 我有时间 :) +1
  • 我刚开始写 C++ 的时间还不到 3 个月。我现在至少可以做的是数组。

标签: c++


【解决方案1】:

这里是好的风格和 C++ 代码:

  • 为相关数据使用结构
  • 使用向量
  • 使用 getline 在输入字段中留出空格
  • 单独的关注点(在读取输入时不要打印输出,从功能的角度来看这是没有意义的)

    int main() {
        Books issued = borrowBooks();
    
        std::cout << "Successfully borrowing " << issued.size() << " books, saving receipt\n";
    
        printReceipt(issued, "IssueRecord.txt");
    }
    
  • 处理错误

作为奖励,我展示了由静态配置的列引导的漂亮打印表:

struct {
    int width;
    std::string header;
} columns[] = { { 10, "ID" }, { 30, "Title" }, { 25, "Author" }, 
                { 25, "Department" }, { 15, "Issuer" } };

Live On Coliru

#include <vector>
#include <fstream>
#include <iomanip>
#include <iostream>

struct Book {
    int id = 0;
    std::string title, department, author, issuer;
};
using Books = std::vector<Book>;

bool promptDetails(Book& book) try {
    std::cin.exceptions(std::ios::failbit);

    std::cout << "Enter Book ID (enter 0 to complete): ";

    if (std::cin >> book.id) {
        std::cin.ignore(1024, '\n');
    }

    if (book.id == 0)
        return false;

    std::cout << "Enter Book Title: ";
    std::getline(std::cin, book.title);

    std::cout << "Enter Book Author: ";
    std::getline(std::cin, book.author);

    std::cout << "Enter Book Department: ";
    std::getline(std::cin, book.department);

    std::cout << "Enter Book Issuer: " << std::endl;
    std::getline(std::cin, book.issuer);

    return true;
} catch(std::exception const& e) {
    std::cout << "Input error (" << e.what() << ")\n";
    return false;
}

Books borrowBooks() {
    Books books;

    while (true) {
        Book book;

        if (!promptDetails(book)) 
            break;

        books.push_back(std::move(book));
    }

    return books;
}

void printReceipt(Books const& receipt, std::string const& fname) {
    std::ofstream out(fname);

    struct {
        int width;
        std::string header;
    } columns[] = { { 10, "ID" }, { 30, "Title" }, { 25, "Author" }, 
                    { 25, "Department" }, { 15, "Issuer" } };

    for (auto& col : columns) out << std::setw(col.width) << col.header << " | ";
    out << "\n" << std::setfill('-');
    for (auto& col : columns) out << std::setw(col.width) << "" << "-+-";
    out << "\n" << std::setfill(' ');

    for (auto& book : receipt) {
        out << std::setw(columns[0].width) << book.id << " | " 
            << std::setw(columns[1].width) << book.title << " | " 
            << std::setw(columns[2].width) << book.author << " | " 
            << std::setw(columns[3].width) << book.department << " | " 
            << std::setw(columns[4].width) << book.issuer << " |" << "\n";
    }

    for (auto& col : columns) out << std::setw(col.width) << std::setfill('-') << "" << "-+-";
    out << "\n";
}

int main() {
    Books issued = borrowBooks();

    std::cout << "Successfully borrowing " << issued.size() << " books, saving receipt\n";

    printReceipt(issued, "IssueRecord.txt");
}

如果输入是

29134
The Hen And Her Trust Issues
Mojit Bunghead
Pop Culture
Central Library
4893
Most Unnecessary
P.H.W. Graftink
Science Fiction
Central Library
6083
Code Of Concoct
Public Domain
Folklore
Central Library
0

输出文件的样子

        ID |                          Title |                    Author |                Department |          Issuer | 
-----------+--------------------------------+---------------------------+---------------------------+-----------------+-
     29134 |   The Hen And Her Trust Issues |            Mojit Bunghead |               Pop Culture | Central Library |
      4893 |               Most Unnecessary |           P.H.W. Graftink |           Science Fiction | Central Library |
      6083 |                Code Of Concoct |             Public Domain |                  Folklore | Central Library |
-----------+--------------------------------+---------------------------+---------------------------+-----------------+-

【讨论】:

猜你喜欢
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多