2021-04-18

不懂就问
C++

在这里插入代码片
//输出函数
void Addres::Show() {
    
    
	if (Abook.size()==1) {
    
    

	}
	else {
    
    
		for (auto itb = Abook.begin(); itb != Abook.end(); ++itb) {
    
    
			cout << "用户姓名:" << setw(7) << itb->first << setw(16) << "用户电话:" << itb->second << endl;
		}
		cout << endl;
	}
}
//构造函数
Addres::Addres() {
    
    
	fstream file(M, ios::in); 
	if (!file.is_open()) {
    
    
		fstream file(M, ios::out);
	}
	else {
    
    
		while (file) {
    
    
			pair<string, string>  User;
			file >> User.first >> User.second;

			Abook.insert(User);
		}

	}

	file.close();
}
		//txt文件内容
//方靖雅      1343272355
 // 张龙     13434482398
 

这样读txt文件 ,为什莫最后结果是
在这里插入图片描述
调试半天发现构造函数在读取文件时,会读取到第三行,将 User.first 和User.second赋值为空。(本来文件读写都不是太懂,现在更不懂了,求大佬)

还有一种情况就是
而产生的文件如下:
haha 5 lala
hehe 5 lele
hihi 5 lili
huhu 5 lulu
读文件运行结果:
haha 5 lala
hehe 5 lele
hihi 5 lili
huhu 5 lulu
huhu 5 lulu
最后一行信息重复

根据网上所查资料,问题应该是当我选择feof判断文件是否结束时 文件最后的回车符也被读入

求解决方案
/*while (fin >> test.x && fin >> test.y && fin >> test.z)
{

		test_list.push_back(test);

	}*/

这是在网上找到的解决办法,详解转https://blog.csdn.net/doupei2006/article/details/84183821?

猜你喜欢

转载自blog.csdn.net/m0_51429482/article/details/115819364
今日推荐