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

本文介绍C++中数字与字符串相互转换的方法,包括使用stringstream进行转换的优点及sprintf、sscanf函数的高效处理方式,并详细解析了sprintf函数的参数与格式说明。

数字转字符串:
用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.
 


本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/touzani/archive/2007/05/24/1623850.aspx

本系统采用Python编程语言中的Flask框架作为基础架构,实现了一个面向二手商品交易的网络平台。该平台具备完整的前端展示与后端管理功能,适合用作学术研究、课程作业或个人技术能力训练的实际案例。Flask作为一种简洁高效的Web开发框架,能够以模块化方式支持网站功能的快速搭建。在本系统中,Flask承担了核心服务端的角色,主要完成请求响应处理、数据运算及业务流程控制等任务。 开发工具选用PyCharm集成环境。这款由JetBrains推出的Python专用编辑器集成了智能代码提示、错误检测、程序调试与自动化测试等多种辅助功能,显著提升了软件编写与维护的效率。通过该环境,开发者可便捷地进行项目组织与问题排查。 数据存储部分采用MySQL关系型数据库管理系统,用于保存会员资料、产品信息及订单历史等内容。MySQL具备良好的稳定性和处理性能,常被各类网络服务所采用。在Flask体系内,一般会配合SQLAlchemy这一对象关系映射工具使用,使得开发者能够通过Python类对象直接管理数据实体,避免手动编写结构化查询语句。 缓存服务由Redis内存数据库提供支持。Redis是一种支持持久化存储的开放源代码内存键值存储系统,可作为高速缓存、临时数据库或消息代理使用。在本系统中,Redis可能用于暂存高频访问的商品内容、用户登录状态等动态信息,从而加快数据获取速度,降低主数据库的查询负载。 项目归档文件“Python_Flask_ershou-master”预计包含以下关键组成部分: 1. 应用主程序(app.py):包含Flask应用初始化代码及请求路径映射规则。 2. 数据模型定义(models.py):通过SQLAlchemy声明与数据库表对应的类结构。 3. 视图控制器(views.py):包含处理各类网络请求并生成回复的业务函数,涵盖账户管理、商品展示、订单处理等操作。 4. 页面模板目录(templates):存储用于动态生成网页的HTML模板文件。 5. 静态资源目录(static):存放层叠样式表、客户端脚本及图像等固定资源。 6. 依赖清单(requirements.txt):记录项目运行所需的所有第三方Python库及其版本号,便于环境重建。 7. 参数配置(config.py):集中设置数据库连接参数、缓存服务器地址等运行配置。 此外,项目还可能包含自动化测试用例、数据库结构迁移工具以及运行部署相关文档。通过构建此系统,开发者能够系统掌握Flask框架的实际运用,理解用户身份验证、访问控制、数据持久化、界面动态生成等网络应用关键技术,同时熟悉MySQL数据库运维与Redis缓存机制的应用方法。对于入门阶段的学习者而言,该系统可作为综合性的实践训练载体,有效促进Python网络编程技能的提升。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值