sscanf与sprintf关于字符串与数字转化的使用

复习前面的内容,觉得这个其实特别有用,记录下来
不过试了下c++的容器,string声明的似乎不能这么用?这里用的是char str[100]这样的字符串

sscanf(str2,"%d\n",&n); 表示将str2中的内容写入数字n,(从左到右)
sprintf(str3,"%d",p); 表示将数字p的内容写入字符串(从右到左)

代码:

#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

int main(){
    
    
	string str;
	cin>>str;    //接收不了string类型声明的 
	char str2[100];
	int n,m;
	cin>>str2;
	sscanf(str2,"%d\n",&n);   //将str2字符串放到数字n中 
	printf("字符串str2-4=%d\n",n-4);
	int p = 333;
	char str3[100];
	sprintf(str3,"%d",p);     //这是把数字p写到字符串数组,注意这不是输出 
	printf("%s",str3);
}

猜你喜欢

转载自blog.csdn.net/weixin_42377217/article/details/104363494