sscanf 和 sprintf 和c_str() 和 str()

掌握c语言 字符串转换     c++字符串转换

注意c_str()返回时 临时变量,存在销毁的可能 所以最好把内容复制了

sscanf用法https://blog.csdn.net/suxiang198/article/details/46836961

#include<iostream>
#include<cstdio>
#include<string>
#include<sstream>

using namespace std;


//c++方法 将double数值 转换成string对象
string convertToString(double x)
{
	ostringstream o;
	if(o<<x)//将x作为string流入o //很像c语言里面的sprintf
		return o.str();//将o中的值转换成string对象
	else
		return "conversion error";//o读取x失败
}

/*c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针
比如:最好不要这样:
char* c;
string s="1234";
c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理

应该这样用:
char c[20];
string s="1234";
strcpy(c,s.c_str());
这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作*/

//c++方法 将string对象转换成double数值;
double convertFromString(string & s)
{
	istringstream is(s);
	double x;
	if(is>>x)//很像c语言里面的sscanf 从流中第一个字符开始分流出一个double
		return x;
	else
		return 0.0;
}




int main(){

	//sscanf()  从第一个字符串参数 写入 第三个参数(取地址)
	char a[100] = "4564.46", b[100] = "4646";
	double a1;
	int b1;
	//sscanf(a + 2, "%lf", &a1);
	sscanf(a + 4, "%lf", &a1);//从小数点开始读  会帮您补0
	//sscanf(b + 3, "%d", &b1);  //不要超过  来读
	sscanf(b, "%d", &b1);
	cout << a1 << endl;
	cout << b1 << endl;


	//sprintf()   从第三个参数 写入 第一个字符串参数(不用取地址)
	double d = 123.46;
	char d1[100];
	int c = 464341;
	char c1[100];
	sprintf(c1, "%d", c);
	cout << c1 << endl;
	sprintf(d1, "%.1lf", d); //可以控制精度(四舍五入好像)  不然默认小数点6位
	cout << d1 << endl;


	string h = "564.134", k = "783143";
	int k1;
	double h1;
	h1 = convertFromString(h), k1 = convertFromString(k);
	cout << h1 << endl;
	cout << k1 << endl;

	string y, u;
	y = convertToString(h1), u = convertToString(k1);
	cout << y << endl;
	cout << u << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/liangnimahanwei/article/details/82915482