输出名称和数字以文件C
Outputting names and numbers to file C++
我的程序能够记录所有名称和数量"数字"您输入并显示给屏幕,我遇到的问题是将所有这些数字和名称保存到文件中。
看来它仅记录并保存您输入的最后一个单词和数字。例如,您输入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;
}
相关文章:
- 如何在C++中确定文本文件中的元素是字符还是数字
- 使用fstream对txt文件中的数字进行循环
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 为什么当我输入较大的数字时,我的程序会到达文件末尾?
- 如何从也包含C++字母的文本文件中提取某些数字?
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 在 txt 文件中显示前两个数字的程序
- 尝试将数字写入二进制文件时引发异常
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- C++:从文件中读取字符串和整数,并获得最大数字
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 如何读取具有数字间隔的文本文件?C++
- 如何知道文本文件中的输入是否是 C++ 中的有效数字
- 如何删除文件中的数字,通过 c++ fstream 的
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 如何从txt文件c++中提取括号之间的数字
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- 如何将数字输出到文件中,所有数字都具有相同的精度
- 如何检索文件数字签名信息