【发布时间】:2014-04-12 05:37:20
【问题描述】:
好吧,伙计们!写入文件时遇到问题。基本上,我的问题是,当我写入文件时,例如变量person.address1 中的2913 Harvey Drive 之类的地址将被写入文件中的单独行而不是一行。我需要它们在一条线上。我做了一些研究,但找不到任何我能理解的东西,所以我希望我能有一个与我的代码相关的例子来帮助我理解。这是我的代码:
int newEntry()
{
string str;
Client person;
char response;
double temp1;
double temp2;
ostringstream strs1;
ostringstream strs2;
//create file object and open file
fstream customer("customer.dat", ios:: out | ios::app);
if (!customer)
{
cout << "Error opening file. Program aborting." << endl;
}
do
{
cout << "Enter client information:" << endl << endl;
cout << "Name: ";
cin >> person.name;
cout << endl;
cout << "Address 1: ";
cin >> person.address1;
cout << endl;
cout << "Address 2: ";
cin >> person.address2;
cout << endl;
cout << "Phone: ";
cin >> person.phone;
cout << endl;
cout << "Acct. Balance: ";
cin >> temp1;
strs1 << temp1;
str = strs1.str();
person.acctBal = str;
cout << endl;
cout << "Last Payment: ";
cin >> temp2;
strs2 << temp2;
str = strs2.str();
person.lastPay = str;
cout << endl;
customer << person.name << endl;
customer << person.address1 << endl;
customer << person.address2 << endl;
customer << person.phone << endl;
customer << person.acctBal << endl;
customer << person.lastPay << endl;
customer << endl; //blank space in file
cout << endl << "Do you want to enter another record? (Enter Y for Yes, N
for No): ";
cin >> response;
//add validation to make sure they enter y or n
cout << endl << endl;
cout << BORDER << endl << endl;
} while (toupper(response) == 'Y');
customer.close();
return 1;
}
我看到了一些关于连接字符串变量然后将整个字符串变量保存到文件的内容,但我不确定我是否也能理解如何读回每一行。下面是读取代码的函数:
int displayAll()
{
vector<Client> store;
string space;
Client foo;
int i = 0;
fstream customer("customer.dat", ios::in);
if (!customer)
{
cout << "Error opening file. Program aborting." << endl;
return 0;
}
while (!customer.eof())
{
store.push_back(foo);
customer >> store[i].name;
customer >> store[i].address1;
customer >> store[i].address2;
customer >> store[i].phone;
customer >> store[i].acctBal;
customer >> store[i].lastPay;
customer >> space;
i++;
}
for (int k = 0; k < i; k++)
{
cout << " Name: " << store[k].name << endl
<< " Address 1: " << store[k].address1 << endl
<< " Address 2: " << store[k].address2 << endl
<< " Phone: " << store[k].phone << endl
<< " Acct. Balance: " << store[k].acctBal << endl
<< " Last Payment: " << store[k].lastPay << endl << endl;
}
cout << BORDER << endl << endl;
customer.close();
return 1;
}
因此,例如,如果我使用了连接方法,例如:
string += person.name;
string += newLine; //newLine would be a variable holding the endl function
string += person.address;
(我不确定我是否理解上面的代码以及它是如何工作的,或者我是否做得对。)
然后将 string 变量保存到文件中,customer >> store[i].name 会存储整行还是只存储空格?
【问题讨论】:
-
如果您想读取整行作为地址,那么 (a) 确保您在前一个字段之后读取换行符,并且 (b) 使用
getline(cin, line)读取该行。此外,您应该检查每一个输入操作。您可能会考虑仅使用行输入,然后通过字符串流将生成的字符串解析到目标变量中——C++ 类似于fgets()加上 C 中的sscanf()。
标签: c++ string file concatenation