Int and string types in C ++ convert each other

Source: Internet
Author: User

C ++ does not call some class methods directly during data type conversion like Java and C #. It is easy to use.

A very simple example is string str = "D :\\ "+1+".txt". This can be used in Java or C # To automatically unpack and package.

But it is not allowed in C ++. Of course this is only one file, but when we want to use the for loop

It may be a bit difficult to name files in 1, 2, 3... folders. Because I have encountered this situation

Write several methods. It may not be the best method, but you have to exercise your skills. If you find any mistakes or have better methods, please feel free to advise.

Method 1: This method is stupid. You can write a function yourself, such as string getString (int value) {}. The implementation is simple and you will not write it.

You can judge and connect the characters one by one, and then return the characters. Similar int getInt (string str) {}, you can set string

To int.

Method 2: Use some C ++ file streams or C functions:

As follows:

/* Conversion between C ++ String and int */# include <iostream> # include <sstream> using namespace std; int main () {/* use atoi in the C standard library * // string to int string str = "123"; int value = std: atoi (str. c_str (); cout <"string to int value:" <value <endl;/* C ++ standard library, using stringstream: (stringstream can be used for conversion between various data types) */std: stringstream sstr; // string to int sstr <"520"; int value2; sstr> value2; cout <"string to int value2:" <value2 <endl; // int to string int value3 = 125; std: stringstream sstr2; sstr2 <value3; string str2; sstr2> str2; cout <"int to string str2:" <str2 <endl; string filepath = "D: \" + str2 + ". txt "; cout <filepath <endl ;}

The result is as follows:

 

 

 

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.