sstream 小tips

本文探讨了一个在C++中使用fstream和stringstream时遇到的问题,即重复使用strstream可能导致的数据丢失。通过分析代码实例,解释了原因并提出了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天写了点垃圾代码,如下:

<span style="white-space:pre">		</span>fstream ifile;
		string thestr;
		stringstream strstream;
		int ele;
		string waste;
		ifile.open(argv[i]);
		getline(ifile,thestr);
		strstream << thestr;
		while (strstream >> ele){
			allelement[i - 1].element.push_back(ele);// allelement 是个struct*的deque,element是struct里面包含的depue
		}
		getline(ifile, thestr);
		strstream.str(thestr);
		strstream >> waste >> allelement[i - 1].priority;
		ifile.close();

运行之后,发现waste和 allelement[i - 1].priority 这两个变量并没有成功写入。


 经过一番分析后发现,原来在用getline写入thestr,然后用thestr写入strstream时,源文件(ifile)中的\n是会被一起写入的,而在strstream>>ele的时候,\n并不会被写入。

 

所以当我继续将strstream输入到waste的时候,由于存储的第一个字符为\n, 所以waste为空,从而导致allelement[i - 1].priority也无法被写入成功。


总之,重复利用strstream的时候,请务必及时使用strstream.clear()清空存储的东西,以保证输入正确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值