C++数字与字符串之间的转换

来源:互联网 发布:java权限管理框架源码 编辑:程序博客网 时间:2024/05/23 01:14

C/C++数字与字符串之间的转换

sprintf函数实现数字与字符串的转换

sprintf()函数定义

sprintf(buffer, "a = %d", a);
#include <iostream>#include <stdio.h>#include <string.h>#include <cstdlib>using namespace std;int main(){    int a, b, c;    scanf("%d%d%d",&a, &b, &c);    printf("a = %d, b = %d, c = %d", a, b, c);    char buffer[256];    memset(buffer, '\0', 256);    sprintf(buffer, "%d", a);    cout << buffer;    system("pause");    return 0;}
char str[10];double a=123.321;sprintf(str,"%.3lf",a);

==itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。==

itoa实现整形转字符

itoa(int, char*, 10);第一个参数是被转的整形,第二是字符串指针,第三个是进制
#include <iostream>#include <stdio.h>#include <string.h>#include <cstdlib>using namespace std;int main(){    int a, b, c;    scanf("%d%d%d",&a, &b, &c);    printf("a = %d, b = %d, c = %d", a, b, c);    char buffer[256];    memset(buffer, '\0', 256);    itoa(a, buffer, 10);    cout << buffer;    system("pause");    return 0;}

字符串转数字

sscanf函数

char str[]="1234321";int a;sscanf(str,"%d",&a);.............char str[]="123.321";double a;sscanf(str,"%lf",&a);.............char str[]="AF";int a;sscanf(str,"%x",&a); //16进制转换成10进制
char temp[256] = "12345";int c = 0;c = atoi(temp);sscanf(temp, "%['\0']", c);cout << c;system("pause");return 0;
另外也可以使用atoi(),atol(),atof().
1、一般用法char buf[512] = ;sscanf("123456 ", "%s", buf);printf("%s\n", buf);结果为:1234562. 取指定长度的字符串。如在下例中,取最大长度为4字节的字符串。sscanf("123456 ", "%4s", buf);printf("%s\n", buf);结果为:12343. 取到指定字符为止的字符串。如在下例中,取遇到空格为止字符串。sscanf("123456 abcdedf", "%[^ ]", buf);printf("%s\n", buf);结果为:1234564. 取仅包含指定字符集的字符串。如在下例中,取仅包含19和小写字母的字符串。sscanf("123456abcdedfBCDEF", "%[1-9a-z]", buf);printf("%s\n", buf);结果为:123456abcdedf5. 取到指定字符集为止的字符串。如在下例中,取遇到大写字母为止的字符串。sscanf("123456abcdedfBCDEF", "%[^A-Z]", buf);printf("%s\n", buf);结果为:123456abcdedf6、给定一个字符串iios/12DDWDFF@122,获取 / 和 @ 之间的字符串,先将 "iios/"过滤掉,再将非'@'的一串内容送到buf中sscanf("iios/12DDWDFF@122", "%*[^/]/%[^@]", buf);printf("%s\n", buf);结果为:12DDWDFF7、给定一个字符串"hello, world",仅保留"world"。(注意:“,”之后有一空格)sscanf(“hello, world”, "%*s%s", buf);printf("%s\n", buf);结果为:world  P.S. %*s表示第一个匹配到的%s被过滤掉,即hello被过滤了,  如果没有空格则结果为NULL。

string转char*

string str;char* ch;char *ch = const_cast<char*>(str.c_str());

char*转string

直接转char *ch = "12345";string str(ch);

字符串操作

strcpy, strcat, strcam

使用stringstream类

ostringstream对象写一个字符串,类似于sprintf()   ostringstream s1;  int i = 22;  s1 << "Hello " << i << endl;  string s2 = s1.str();  cout << s2;用istringstream对象读一个字符串,类似于sscanf()   istringstream stream1;  string string1 = "25";  stream1.str(string1);  int i;  stream1 >> i;  cout << i << endl;  // displays 25
0 0
原创粉丝点击