输出名称和数字以文件C

Outputting names and numbers to file C++

本文关键字:文件 数字 输出      更新时间:2023-10-16

我的程序能够记录所有名称和数量"数字"您输入并显示给屏幕,我遇到的问题是将所有这些数字和名称保存到文件中。

看来它仅记录并保存您输入的最后一个单词和数字。例如,您输入4个名称和4个不同的数字,它将仅保存姓氏输入和数字,而不是第一个输入。

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;
struct bank_t {
  string name;
  int money;
} guests[100];  // **guests name = maximum number of names to enter**
void printcustomer (bank_t nombres);  // **bank_t nombres = names**
int main ()
{
  string amount;  //** amount to enter**
  int n;
  int i;  //** number of customers **
  //int i=3;
    cout<<"Please enter the amount of customers";
    cout<<" then press 'ENTER' n";
    cin >> i;  // **will take what ever amount of names you decide to input **
    cin.get();
  for (n=0; n<i; n++)
  {
    cout << "n Enter the name of customer: n";
    getline (cin,guests[n].name);
    cout << "n Enter the amount of money: n $: ";
    getline (cin,amount);
    stringstream(amount) >> guests[n].money;
  }
  cout << "n You have entered these names:n";
  for (n=0; n<i; n++)
    printcustomer (guests[n]);
  return 0;
}
void printcustomer (bank_t nombres)
{
    cout << nombres.name;  //** display the final names **
    cout << "  $" << nombres.money << " Dollars"<< "n"; //** display the final amount **
    ofstream bank_search;
    bank_search.open ("alpha.dat");
    //bank_search.write << nombres.name ;
    bank_search << nombres.money;
    bank_search.close();    
}

看来它仅记录并保存您输入的最后一个单词和数字。

您正在打开并关闭要编写的每个记录的文件,并覆盖先前写的一个!

您需要以附加模式打开文件(请参阅std::ios_base::app),或在main()中的循环外打开一次,然后将ofstream作为参数传递给每个printcustomer()函数调用(该调用都会好一些)。/p>

void printcustomer (bank_t nombres)
{
    cout << nombres.name;  //** display the final names **
    //** display the final amount **
    cout << "  $" << nombres.money << " Dollars"<< "n"; 
    ofstream bank_search;
    bank_search.open ("alpha.dat", std::ios_base::app); // Note the append mode!
    //bank_search.write << nombres.name ;
    bank_search << nombres.money;
    bank_search.close();    
}

如图所示的情况不是很高效,因为打开和关闭文件是一个相对昂贵的操作。一个更好的解决方案是打开文件一次,并附加所有新输入的记录:

ofstream bank_search("alpha.dat", std::ios_base::app);
cout << "n You have entered these names:n";
for (n=0; n<i; n++)
{
    printcustomer (bank_search,guests[n]);
}
bank_search.close();    

void printcustomer (ofstream& bank_search, bank_t nombres)
{
    bank_search << nombres.name;
    bank_search << nombres.money;
}