gpt4 book ai didi

c++ - 将名称和数字输出到文件 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:14 25 4
gpt4 key购买 nike

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

它似乎只记录并保存你最后输入的单词和数字到文件中。例如你输入 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();

}

最佳答案

It seems that it only records and saves the last words and numbers you input into a file.

您正在为每条要写入的记录打开和关闭文件,并覆盖之前写入的记录!

您需要以附加模式打开您的文件(参见 std::ios_base::app ),或者在 main() 的循环外打开它一次,并传递 ofstream 作为每个 printcustomer() 函数调用的参数(这会执行得更好)。

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;
}

关于c++ - 将名称和数字输出到文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com