【发布时间】:2014-03-08 04:52:08
【问题描述】:
在我的代码中:
int newEntry()
{
string input;
Client person;
char response = 'y';
//create file object and open file
fstream customer("customer.dat", ios::out | ios::app);
if (!customer)
{
cout << "Error opening file. Program aborting." << endl;
return 0;
}
do
{
cout << "Enter person information:" << endl << endl;
cout << "Name: " << endl;
getline(cin, input);
strcpy(person.name, input.c_str());
cout << endl << "Street Adress (And Apartment Number):" << endl;
cin >> person.address1;
getline(cin, input);
strcpy(person.address1, input.c_str());
cout << endl << "City, State, Zipcode: " << endl;
cin >> person.address2;
getline(cin, input);
strcpy(person.address2, input.c_str());
cout << endl << "Phone: " << endl;
cin >> person.phone;
getline(cin, input);
strcpy(person.phone, input.c_str());
cout << endl << "Account Balance: " << endl;
cin >> person.acctBal;
//input validation to ensure a non neg number
cin.ignore();
cout << endl << "Last Payment: " << endl;
cin >> person.lastPay;
//input validation to ensure a non neg number
customer.write(reinterpret_cast<char *>(&person),
sizeof(person));
cout << endl << "Do you want to enter another record? (Enter Y for Yes, N
for No) " << endl;
cin >> response;
cout << "_______________________________________________" << endl << endl;
if (toupper(response) == 'Y')
{
cin.ignore();
}
} while (toupper(response) == 'Y');
customer.close();
return 1;
}
好像是块:
cout << endl << "Street Address (And Apartment Number):" << endl;
cin >> person.address1;
getline(cin,input);
strcpy(person.address1, input.c_str());
和它的相邻地址 2 提示(相同)导致错误输出到文件时
customer.write(reinterpret_cast<char *>(&person),sizeof(person));
用于写入文件。输出缺少第一个单词。例如,如果输入“211 Harvey Road”,则 211 将被切断。另一个例子,如果输入了“Harvey Road”,那么似乎“harvey”被切断了。当(在另一个函数中)读取文件时,数组的结构缺少开头,以及文件。
最重要的是,在文本文件中,这是写入其中的数据:
Frank Palmasani ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ Harvey Road ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ Haven, Alabama ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ 504617772 ÌÌÌÌ èŽ@ èŽ@James Harris ni ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ Street AVEN ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ China. Alabama ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ 546457474 ÌÌÌÌ ð? ð?
如您所见,Ì 弹出的位置是文件和程序以某种方式丢失第一个单词的位置。我已经尝试了我能想到的一切来解决这个问题,希望其他人也遇到了类似的问题。
我尝试更改将数组结构中保存的数据保存到文件的方法,但发现我无法从一个大分组中的文件中读取。在我的教科书中,使用了我用来读出文件的方法,因此我认为我应该遵循这种方法。
但是,我正在考虑在每一行上分别编写每个,并按顺序精确保存,以便我可以以相同的顺序读取它,将其保存到向量结构中。同样,我想避免这种情况,但很想听听您对此事的看法,无论您是否能够在这里帮助我。
如果您需要,这是我的结构:
const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14;
struct Client
{
char name[NAME_SIZE];
char address1[ADDR_SIZE];
char address2[ADDR_SIZE];
char phone[PHONE_SIZE];
double acctBal;
double lastPay;
};
【问题讨论】:
标签: c++ file text-files output