stringstream不能输入空格_vs2005

chenguangxing3 2013-12-12 11:29:31
vs2005
当字符串带空格时,stringstream就在空格处截断了,上网查了一下,试了下面两种方法都不灵,一种是ss1.unsetf(std::ios::skipws);, 一种是ss2 >> std::noskipws >> str;
哪位知道还有更好的方法吗?

std::string str;
std::stringstream ss1;
ss1.unsetf(std::ios::skipws);
ss1 << "111 222";
ss1 >> str;
AfxMessageBox( str.c_str() );

std::stringstream ss2;
ss2 << std::noskipws << "aaa bbb";
ss2 >> std::noskipws >> str;
AfxMessageBox( str.c_str() );

有个老贴,跟我情况一样: http://bbs.csdn.net/topics/300197237 不过没答案
...全文
620 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
mujiok2003 2013-12-12
  • 打赏
  • 举报
回复
试试看:
#include <sstream>
#include <string>
#include <iterator>
#include <iostream>

int main()
{
  std::string str;
  std::istringstream ss1("111 222"); 
  ss1.unsetf(std::ios::skipws); 
  std::istream_iterator<char> start(ss1), end;
  str.assign(start,end);
  std::cout << str << std::endl;
  return 0;
}
derekrose 2013-12-12
  • 打赏
  • 举报
回复
std::getline(ss1, str); 或者 str = ss1.str();
mujiok2003 2013-12-12
  • 打赏
  • 举报
回复
template<class _Elem,
	class _Traits,
	class _Alloc> inline
	basic_istream<_Elem, _Traits>& operator>>(
		basic_istream<_Elem, _Traits>&& _Istr,
		basic_string<_Elem, _Traits, _Alloc>& _Str)
	{	// extract a string
	typedef ctype<_Elem> _Ctype;
	typedef basic_istream<_Elem, _Traits> _Myis;
	typedef basic_string<_Elem, _Traits, _Alloc> _Mystr;
	typedef typename _Mystr::size_type _Mysizt;

	ios_base::iostate _State = ios_base::goodbit;
	bool _Changed = false;
	const typename _Myis::sentry _Ok(_Istr); //这里也会跳过空格哦

	if (_Ok)
		{	// state okay, extract characters
		const _Ctype& _Ctype_fac = _USE(_Istr.getloc(), _Ctype);
		_Str.erase();

		_TRY_IO_BEGIN
		_Mysizt _Size = 0 < _Istr.width()
			&& (_Mysizt)_Istr.width() < _Str.max_size()
				? (_Mysizt)_Istr.width() : _Str.max_size();
		typename _Traits::int_type _Meta = _Istr.rdbuf()->sgetc();

		for (; 0 < _Size; --_Size, _Meta = _Istr.rdbuf()->snextc())
			if(_Traits::eq_int_type(_Traits::eof(), _Meta))
				{	// end of file, quit
				_State |= ios_base::eofbit;
				break;
				}
                       //跳过whitespace,noskipws对其不管用
			else if (_Ctype_fac.is(_Ctype::space,
				_Traits::to_char_type(_Meta)))
				break;	// whitespace, quit
			else
				{	// add character to string
				_Str.append(1, _Traits::to_char_type(_Meta));
				_Changed = true;
				}
		_CATCH_IO_(_Istr)
		}

	_Istr.width(0);
	if (!_Changed)
		_State |= ios_base::failbit;
	_Istr.setstate(_State);
	return (_Istr);
	}
  • 打赏
  • 举报
回复
如果要取出所有字符,使用
std::string str = ss1.str()
如果自定义分隔符,使用
char separator;//自己的分隔符
while(std::getline(ss1, str, separator))
{
//do something
}
qq120848369 2013-12-12
  • 打赏
  • 举报
回复
他就是用来按空白符分词的,没有其他能力。

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧