c/c++ 数字转成字符串, 字符串转成数字

数字转字符串:
用C++的streanstream:
#include <sstream>
#Include <string>
string num2str(double i)
...{
        stringstream ss;
        ss<<i;
        return ss.str();
}
字符串转数字:

int str2num(string s)
 ...{  
        int num;
        stringstream ss(s);
        ss>>num;
        return num;
}
上面方法很简便, 缺点是处理大量数据转换速度较慢..
C library中的sprintf, sscanf 相对更快

可以用sprintf函数将数字输出到一个字符缓冲区中. 从而进行了转换...
例如:
已知从0点开始的秒数(seconds) ,计算出字符串"H:M:S",  其中H是小时, M=分钟,S=秒
         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:%d", H, M, S);             // 将整数转换成字符串
        time_str=ctime;                                                 // 结果

与sprintf对应的是sscanf函数, 可以将字符串转换成数字
    char    str[] = "15.455";
    int     i;
    float     fp;
    sscanf( str, "%d", &i );         // 将字符串转换成整数   i = 15
    sscanf( str, "%f", &fp );      // 将字符串转换成浮点数 fp = 15.455000
    //打印
    printf( "Integer: = %d ",  i+1 );
    printf( "Real: = %f ",  fp+1 );
    return 0;

输出如下:
Integer: = 16
 Real: = 16.455000


下面是msdn 8.0 关于sprintf函数

#include <stdio.h>int main()...{   char  buffer[200], s[] = "computer", c = 'l';   int   i = 35, j;   float fp = 1.7320534f;   // Format and print various data:    j  = sprintf( buffer,     "   String:    %s", s ); // C4996   j += sprintf( buffer + j, "   Character: %c", c ); // C4996   j += sprintf( buffer + j, "   Integer:   %d", i ); // C4996   j += sprintf( buffer + j, "   Real:      %f", fp );// C4996   // Note: sprintf is deprecated; consider using sprintf_s instead   printf( "Output:%scharacter count = %d", buffer, j );}Output:   String:    computer   Character: l   Integer:   35   Real:      1.732053int sprintf(   char *buffer,   const char *format [,      argument] ... );buffer
Storage location for output

format
Format-control string

argument
Optional arguments

Return typesprintf returns the number of bytes stored in buffer, not counting the terminating null character.character count = 79关于格式(format)


A format specification, which consists of optional and required fields, has the following form:

%[flags] [width] [.precision] [{h | l | ll | I | I32 | type

Flags:


The first optional field of the format specification is flags. A flag directive is a character that justifies output and prints signs, blanks, decimal points, and octal and hexadecimal prefixes. More than one flag directive may appear in a format specification.

Flag Characters
Flag  Meaning  Default 

 Left align the result within the given field width.
 Right align.
 
+
 Prefix the output value with a sign (+ or –) if the output value is of a signed type.
 Sign appears only for negative signed values (–).
 
0
 If width is prefixed with 0, zeros are added until the minimum width is reached. If 0 and – appear, the 0 is ignored. If 0 is specified with an integer format (i, u, x, X, o, d) and a precision specification is also present (for example, %04.d), the 0 is ignored.
 No padding.
 
blank (' ')
 Prefix the output value with a blank if the output value is signed and positive; the blank is ignored if both the blank and + flags appear.
 No blank appears.
 
#
 When used with the o, x, or X format, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively.
 No blank appears.
 
 When used with the e, E, f, a or A format, the # flag forces the output value to contain a decimal point in all cases.
 Decimal point appears only if digits follow it.
 
 When used with the g or G format, the # flag forces the output value to contain a decimal point in all cases and prevents the truncation of trailing zeros.

Ignored when used with c, d, i, u, or s.
 Decimal point appears only if digits follow it. Trailing zeros are truncated.
 

width:

The second optional field of the format specification is the width specification. The width argument is a nonnegative decimal integer controlling the minimum number of characters printed. If the number of characters in the output value is less than the specified width, blanks are added to the left or the right of the values — depending on whether the – flag (for left alignment) is specified — until the minimum width is reached. If width is prefixed with 0, zeros are added until the minimum width is reached (not useful for left-aligned numbers).

The width specification never causes a value to be truncated. If the number of characters in the output value is greater than the specified width, or if width is not given, all characters of the value are printed

 


Character  Type  Output format 
c
 int or wint_t
 When used with printf functions, specifies a single-byte character; when used with wprintf functions, specifies a wide character.
 
C
 int or wint_t
 When used with printf functions, specifies a wide character; when used with wprintf functions, specifies a single-byte character.
 
d
 int
 Signed decimal integer.
 
i
 int
 Signed decimal integer.
 
o
 int
 Unsigned octal integer.
 
u
 int
 Unsigned decimal integer.
 
x
 int
 Unsigned hexadecimal integer, using "abcdef."
 
X
 int
 Unsigned hexadecimal integer, using "ABCDEF."
 
e
 double
 Signed value having the form [ – ]d.dddd e [sign]dd[d] where d is a single decimal digit, dddd is one or more decimal digits, dd[d] is two or three decimal digits depending on the output format and size of the exponent, and sign is + or –.
 
E
 double
 Identical to the e format except that E rather than e introduces the exponent.
 
f
 double
 Signed value having the form [ – ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.
 
g
 double
 Signed value printed in f or e format, whichever is more compact for the given value and precision. The e format is used only when the exponent of the value is less than –4 or greater than or equal to the precision argument. Trailing zeros are truncated, and the decimal point appears only if one or more digits follow it.
 
G
 double
 Identical to the g format, except that E, rather than e, introduces the exponent (where appropriate).
 
a
 double
 Signed hexadecimal double precision floating point value having the form [−]0xh.hhhh p±dd, where h.hhhh are the hex digits (using lower case letters) of the mantissa, and dd are one or more digits for the exponent. The precision specifies the number of digits after the point.
 
A
 double
 Signed hexadecimal double precision floating point value having the form [−]0Xh.hhhh P±dd, where h.hhhh are the hex digits (using capital letters) of the mantissa, and dd are one or more digits for the exponent. The precision specifies the number of digits after the point.
 
n
 Pointer to integer
 Number of characters successfully written so far to the stream or buffer; this value is stored in the integer whose address is given as the argument. See Security Note below.
 
p
 Pointer to void
 Prints the address of the argument in hexadecimal digits.
 
s
 String
 When used with printf functions, specifies a single-byte–character string; when used with wprintf functions, specifies a wide-character string. Characters are printed up to the first null character or until the precision value is reached.
 
S
 String
 When used with printf functions, specifies a wide-character string; when used with wprintf functions, specifies a single-byte–character string. Characters are printed up to the first null character or until the precision value is reached.
 

Note   If the argument corresponding to %s or %S is a null pointer, "(null)" will be printed.

Note   In all exponential formats, the default number of digits of exponent to display is three. Using the _set_output_format function, the number of digits displayed may be set to two, expanding to three if demanded by the size of exponent.

Security Note   The %n format is inherently insecure and is disabled by default; if %n is encountered in a format string, the invalid parameter handler is invoked as described in Parameter Validation. To enable %n support, see _set_printf_count_output.

Precision:printf( "%.0d", 0 );      /* No characters output */How Precision Values Affect Type
Type  Meaning  Default 
a, A
 The precision specifies the number of digits after the point.
 Default precision is 6. If precision is 0, no point is printed unless the # flag is used.
 
c, C
 The precision has no effect.
 Character is printed.
 
d, i, u, o, x, X
 The precision specifies the minimum number of digits to be printed. If the number of digits in the argument is less than precision, the output value is padded on the left with zeros. The value is not truncated when the number of digits exceeds precision.
 Default precision is 1.
 
e, E
 The precision specifies the number of digits to be printed after the decimal point. The last printed digit is rounded.
 Default precision is 6; if precision is 0 or the period (.) appears without a number following it, no decimal point is printed.
 
f
 The precision value specifies the number of digits after the decimal point. If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.
 Default precision is 6; if precision is 0, or if the period (.) appears without a number following it, no decimal point is printed.
 
g, G
 The precision specifies the maximum number of significant digits printed.
 Six significant digits are printed, with any trailing zeros truncated.
 
s, S
 The precision specifies the maximum number of characters to be printed. Characters in excess of precision are not printed.
 Characters are printed until a null character is encountered.
 


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/touzani/archive/2007/05/24/1623850.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值