C + + string and other type interchange

Source: Internet
Author: User

How do you implement string and other types of interchange in C + +? The best way to do this is to use StringStream, which is briefly described below:

1. Convert other types to string

#include <sstream>

StringStream Sstr;

string S1;
S1.append ("string");
Sstr << 12;
Sstr >> s1;//The result is that the value of the original string is flushed out
S1 + = Sstr.str ();//This will not change the original value
Sstr.clear ();//If you want to implement multiple types of conversions by using the same StringStream object, be aware that you must call the clear () member function after each conversion. If not clear, the value will always be there.
cout << s1 << Endl;

2.string conversion to other types

string s = "17";

StringStream SS;
ss<<s; Read-in value

int i;
ss>>i; Output value
cout<<i<<endl; 17

Sstr.clear ();

String name = "Colinguan";
Char cname[200];

StringStream Sstr;
sstr<<name; Read-in value
sstr>>cname; Output conversion Value

C + + string and other type interchange

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.