c++之string學習(更新中)

來源:互聯網
上載者:User

標籤: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學習(更新中)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.