今天看了看c++ cookbook,看到了一个很有用的东西,stringstream,可以很方便的完成连接字符串,进制转换,格式控制等工作.位于sstream.h中

# include <iostream>
# include <iomanip>
# include <string>
# include <sstream>
 
using namespace std;
 
int main()
{
    stringstream ss;
    ss << "There are " << 9 << " apples in my cart.";
    cout << ss.str() << endl;
 
    ss.str("");
    ss << showbase << hex << 16;
    cout << ss.str() << endl;
 
    ss.str("");
    ss << setprecision(4) << 3.1415927;
    cout << ss.str() << endl;
 
    cin >> ss.str();
}

使用初始化:

stringstream.str("..")

其他使用的方式就和输入输出流几乎一样了,使用iomanip里面的控制字可以使得输出不同的格式.使用ss.str()可以得到相应的字符串.

比如

    ss << showbase << hex << 16;

 

就表示

    1) 输出进制的符号(此处为0x)

    2) 输出16进制(hex)


另一个示例:

double SciToDub(const string& str)
{
    stringstream ss(str);
    double d = 0;
    ss >> d;
 
    if (ss.fail())
    {
        //add code to solve the exception
    }
 
    return d;
}

此处调用stringstream >> double的方法,可以完成将科学计数法表示的string转换到double中,而且通过查看stringstream.fail()可以知道是否转换成功

相关文章:

  • 2021-06-27
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
  • 2021-07-30
  • 2021-08-15
猜你喜欢
  • 2021-04-21
  • 2021-05-14
  • 2022-12-23
  • 2021-10-29
  • 2021-08-25
  • 2021-06-12
  • 2021-10-17
相关资源
相似解决方案