C ++ string, character array, and number Conversion

Source: Internet
Author: User

Small things are often very troublesome, that is, they want to use the method of accumulating image indexes to store images. Paste a small piece of code

// Image index No. int ImageIndex = 0; int main (){....... // numeric conversion to string ImageIndex ++; string Index; char index [10]; sprintf_s (index, "% d", ImageIndex); Index = index; string ImageFile = "D: \ test" + Index + ". jpg "; cvSaveImage (& ImageFile [0], & storeImage );.......}

There are two methods to convert a number to a string: one is to use the serial stream under the string; the other is the sprintf and sscanf methods under the C;

Method 1:

Use C ++'s streanstream:

# Include <sstream>
# Include <string>
String num2str (double I)
{
Stringstream ss;
Ss <I;
Return ss. str ();
}

String to numeric:

Int str2num (string s)
{
Int num;
Stringstream ss (s );
Ss> num;
Return num;
}

Method 2:

Sprintf and sscanf in C library are relatively faster

You can use the sprintf function to output the number to a character buffer, and convert the number...
For example:
It is known that the number of seconds (seconds) starting from 0 is calculated as the string "H: M: S", where H is hour, M = minute, S = Second

Int H, M, S;
String time_str;
H = seconds/3600;
M = (seconds % 3600)/60;
S = (seconds % 3600) % 60;
Char ctime [10];
Sprintf (ctime, "% d: % d", H, M, S); // converts an integer to a string
Time_str = ctime; // result

The sscanf function corresponds to sprintf, which can convert strings into numbers.

Char str [] = "15.455 ";
Int I;
Float fp;
Sscanf (str, "% d", & I); // converts a string to an integer I = 15
Sscanf (str, "% f", & fp); // convert the string to a floating point fp = 15.455000
// Print
Printf ("Integer: = % d", I + 1 );
Printf ("Real: = % f", fp + 1 );
Return 0; finally, the first parameter of the cvSaveImage method is of the char * type, and the char * bb = & ImageFile [0] Method for converting a string to a character array;
Related Article

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.