我正在尝试阅读直到文件结尾的电话本应用程序,即从C转换为C++.当我打印文件的结果时,我得到这个:
johnny smith
(Home)3
(Cell)4
x?> x?>
(Home)4
(Cell)4
Run Code Online (Sandbox Code Playgroud)
它应该打印:
johnny smith
(Home)3
(Cell)4
Run Code Online (Sandbox Code Playgroud)
现在我正在使用while(!infile.eof())我读过的是一个糟糕的做法,但是当我使用时,infile.getline()我会重复使用名字和姓氏,并且格式全部被抬起.无论如何(或其他方式)摆脱输入结束时的垃圾或其他方式阅读直到C++文件结束修复此问题.我一直在阅读有关不同解决方案的内容,但很多网站似乎都同意fgets这一点,这就是我对原始C版本所拥有的内容,但显然fgets不适ifstream用于我正在使用的内容.这是代码:
void contacts:: readfile(contacts*friends ,int* counter, int i,char buffer[],char user_entry3[])
{
ifstream read;
read.open(user_entry3,ios::in);
int len;
contacts temp;
*counter=0;
i=0;
while (!read.eof()) {
temp.First_Name=(char*)malloc(36);
temp.Last_Name=(char*)malloc(36);
read>>temp.First_Name>>temp.Last_Name;
read>>buffer;
len=strlen(buffer);
if(buffer[len-1]=='\n')
buffer[len-1]='\0';
temp.home=(char*)malloc(20);
strcpy(temp.home, buffer);
read>>buffer;
len=strlen(buffer);
if(buffer[len-1]=='\n')
buffer[len-1]='\0';
temp.cell=(char*)malloc(20);
strcpy(temp.cell, buffer);
friends[i].First_Name=(char*)malloc(MAXNAME);
friends[i].Last_Name=(char*)malloc(MAXNAME);
friends[i].home=(char*)malloc(MAXPHONE);
friends[i].cell=(char*)malloc(MAXPHONE);
//adds file content to the structure
strcpy(friends[*counter].First_Name,temp.First_Name);
strcpy(friends[*counter].Last_Name,temp.Last_Name);
strcpy(friends[*counter].home,temp.home);
strcpy(friends[*counter].cell,temp.cell);
(*counter)++;
i++;
}
//closes file and frees memory
read.close();
free(temp.Last_Name);
free(temp.First_Name);
free(temp.home);
free(temp.cell);
}
Run Code Online (Sandbox Code Playgroud)
千万不能使用eof(),以确定是否到达文件末尾.而是,阅读您想要阅读的内容,然后检查您是否成功读取了数据.eof()在生成有关格式错误的错误报告之前,您可以使用Obce读取失败来确定错误是否已达到文件末尾.
既然你提到你认为使用!infile.eof()是好的做法:你能指出我们这个错误信息的来源吗?此信息需要更正.
不要用__CODE__.它检查上次读取失败是否是由于到达文件末尾.它不能预测未来.
不要__CODE__在C++中使用.如果这样做,请检查错误的返回值!
不要使用__CODE__为__CODE__.没有大小检查,所以只是要求缓冲区溢出.
在__CODE__上缓冲检查是无用的.__CODE__因为字符串在空格处停止.
你是盲目地将__CODE__一个未知长度的字符串变成__CODE__大小为20.这是另一个缓冲区溢出.
......我有点停止在那里读书.如果你想从文件中读取东西但是停止在eof/error上,你可以这样做:
.
__PRE__
| 归档时间: |
|
| 查看次数: |
30471 次 |
| 最近记录: |