gpt4 book ai didi

c++ - 我试图删除文本文件中的一行时留下回车符

转载 作者:行者123 更新时间:2023-11-30 05:32:23 26 4
gpt4 key购买 nike

在下面的函数中,我创建了一个键,然后在输入文件中搜索它。该函数输出它读取的每一行,除非它与键匹配。

除了在复制最后一条记录后 endl 在文本文件上留下一个回车符外,该函数似乎可以正常工作。当我随后读取文件时,由于返回,它读取了最后一行两次。

我尝试使用空格,结果完全相同。有没有一种方法可以在 while 语句运行后删除最后一个空格或返回?还是我可以避免在最后一条记录上写空格或返回?

void deleteAddress(){
ifstream infile( "addressbook.txt", ios::in);
ofstream outfile ("ACopy.txt", ios::out);

string last, first, address1, address2, address3, address4;
string address5, address6, bday, anniversary, delL, delF;
int key, keyDel;

cout<<"Enter the name of the the client you want to delete (format: last, first)"<<endl;
cin>> delL >> delF;

keyDel = createKey(delL,delF);

while(! infile.eof()) {
(infile >> last >> first >> address1 >> address2 >>
address3 >> address4 >> address5 >> address6 >>
bday >> anniversary);

key = createKey(last, first);

if(key != keyDel) {
outfile << last << " "<<first << " "<<address1 << " " <<
address2 << " "<<address3 << " "<<address4 <<
" "<<address5 << " "<<address6 << " "<<bday <<
" "<<anniversary<<endl;
}
}
outfile.close();
infile.close();
}

下面是我正在使用的显示函数(displauCopy)和createKey:

void displayCopy(){
string line;
string last, first, address1, address2, address3;
string address4, address5, address6, bday, anniversary;
ifstream infile("ACopy.txt");

cout<<"First" << std::setfill(' ')<<setw(15) << "Last" <<endl;

while(! infile.eof())
{
(infile >> last >> first >> address1 >> address2 >>
address3 >> address4 >> address5 >> address6 >>
bday >> anniversary);

cout<< last <<", "<<first<<" "<<address1<<" "
<<address2<<" "<<address3<<", "<<address4<<", "
<<address5<<" "<<address6<<" "<<bday<<" "<<anniversary<<endl;
}
infile.close();
}

int createKey (string first, string last) {
int key;
key = (int)last[0]+(int)last[1]+(int)last[2]+(int)first[0];
return key;
}

最佳答案

问题是你在 EOF-test 上循环,这是个坏主意。

你甚至不检查你的输入是否成功,所以即使它失败了(因为流没有错误,但里面什么都没有),你仍然会输出一些东西。而且因为这些字符串在循环之外的范围内,所以它们包含最后一次迭代放入其中的任何内容。

您可以进行以下小修改,而不是在 EOF-test 上循环:

while( infile >> last >> first >> address1 >> address2 >> address3
>> address4 >> address5 >> address6 >> bday >> anniversary )
{
cout<< last <<", "<<first<<" "<<address1<<" "
<<address2<<" "<<address3<<", "<<address4<<", "
<<address5<<" "<<address6<<" "<<bday<<" "<<anniversary<<endl;
}

或者,如果所有内容都在一行中,您可以使用 std::getline 然后从字符串流中读出:

int line_num = 0;
string line;
while( getline( infile, line ) )
{
++linenum;
istringstream iss( line );

if( iss >> last >> first >> address1 >> address2 >> address3
>> address4 >> address5 >> address6 >> bday >> anniversary )
{
cout<< last <<", "<<first<<" "<<address1<<" "
<<address2<<" "<<address3<<", "<<address4<<", "
<<address5<<" "<<address6<<" "<<bday<<" "<<anniversary<<endl;
}
else
{
cerr << "Error reading line " line_num << " : " << line << endl;
}
}

关于c++ - 我试图删除文本文件中的一行时留下回车符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35145742/

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