码迷,mamicode.com
首页 > 编程语言 > 详细

c++之string学习(更新中)

时间:2018-05-25 01:35:24      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:created   previous   stream   ring   str   turn   any   equal   eal   

一:stringstream clear与str("")的问题

因为oj平台需要制作.in .out这样的测试数据,如果偶尔制作到没啥,可题量一大就会出问题,所以我想通过fstream 自动生成这些文件,并使文件名持续增大。

像1.in 2.in 3.in…… 这就涉及到了int类型与string 类型相互转换的问题,通过并不友善的度娘的搜索,我学到了一个方法。 

通过stringstream类来进行int 和string 的转换。 
stringstream的头文件是sstream 

我发现重复写入时会出现前面的东西还留在stream中。 
这时,我首先想到的是clear()函数,这个函数是用来清空流的。 
但通过string = stream.str()进行值传递操作时,旧的数据依然存在, 
而通过stream>>string时,旧的数据就不会存在。 

string test;
string test2;
stringstream ss;

for(int j=0;j<10;j++)
{
  ss.clear();
  //ss.str("");
  ss<<j;
  test = ss.str();
  ss>>test2;
  cout <<test<<" "<<ss.str()<<" "<<test2<<endl;
}

stringstream常用来安全的格式化若干个字符串,数值到一个缓冲区, 而不用担心溢出, 可以用来取代snprintf. 但是很多人都在使用stringstream的时候遇到因为stringstream内部的缓冲区没有正确的清空导致的问题. 
那么把stringstream类内部的缓冲区正确的清空方式是什么呢? stringstream ss; 答案是: ss.str(“”) 
方法. 另外,如果需要把格式化后的字符串通过>>输出到字符串, 必须每次都调用clear()方法! 所以, 保险期间, 每次缓冲区格式化后, 
都通过clear(), str(“”) 两个函数都调用, 把stingstream类复位.

所以说,当重复使用streamstring类的对象的时候先调用clear(), str(“”) 这两个函数, 把stingstream类复位.,然后在用streamstring类进行数据的转换。

PS1: 网上有一些讨论, 说ss.str("")方法不管用, 而通过 ss.str().clear(); 这可能是c++标准库的实现方法不一致导致. 可以自行看下代码库引用的sstream文件的源码.
       在我的linux机器上, /usr/include/c++/4.1.0/sstream, 以及vs2008的实现, 都是和本文是一致的.
PS2: 注意str() 和 str("") 的区别
       str() 是返回内部缓冲区的一个copy, str("") 是清空内部缓冲区.

 

最后,附上str和str()内部的源码实现

/**
* @brief Setting a new buffer.
* @param s The string to use as a new sequence.
*
* Deallocates any previous stored sequence, then copies @a s to
* use as a new one.
*/
void str(const __string_type& __s)
{
  // Cannot use _M_string = __s, since v3 strings are COW.
  _M_string.assign(__s.data(), __s.size());
  _M_stringbuf_init(_M_mode);
}

 

// Get and set:
/**
* @brief Copying out the string buffer.
* @return A copy of one of the underlying sequences.
*
* "If the buffer is only created in input mode, the underlying
* character sequence is equal to the input sequence; otherwise, it
* is equal to the output sequence." [27.7.1.2]/1
*/
__string_type
str() const
{
  __string_type __ret;
  if (this->pptr())
  {
    // The current egptr() may not be the actual string end.
    if (this->pptr() > this->egptr())
    __ret = __string_type(this->pbase(), this->pptr());
    else
    __ret = __string_type(this->pbase(), this->egptr());
  }
  else
    __ret = _M_string;
    return __ret;
}

 

c++之string学习(更新中)

标签:created   previous   stream   ring   str   turn   any   equal   eal   

原文地址:https://www.cnblogs.com/tianzeng/p/9085968.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!