sprintf,scanf

1、sprintf函数

sprintf函数原型为 int sprintf(char *str, const char *format, …)。作用是格式化字符串,具体功能如下所示:

(1)将数字变量转换为字符串。

(2)得到整型变量的16进制和8进制字符串。

(3)连接多个字符串。

举例如下所示:


 1     char str[256] = {
    
     0 };
 2     int data = 1024;
 3     //将data转换为字符串
 4     sprintf(str,"%d",data);
 5     //获取data的十六进制
 6     sprintf(str,"0x%X",data);
 7     //获取data的八进制
 8     sprintf(str,"0%o",data);
 9     const char *s1 = "Hello";
10     const char *s2 = "World";
11     //连接字符串s1和s2
12     sprintf(str,"%s %s",s1,s2);

2、sscanf函数

sscanf函数原型为int sscanf(const char *str, const char *format, …)。将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内。具体功能如下:

(1)根据格式从字符串中提取数据。如从字符串中取出整数、浮点数和字符串等。

(2)取指定长度的字符串

(3)取到指定字符为止的字符串

(4)取仅包含指定字符集的字符串

(5)取到指定字符集为止的字符串

sscanf可以支持格式字符%[]:

 1     const char *s = "http://www.baidu.com:1234";
 2     char protocol[32] = {
    
     0 };
 3     char host[128] = {
    
     0 };
 4     char port[8] = {
    
     0 };
 5     sscanf(s,"%[^:]://%[^:]:%[1-9]",protocol,host,port);
 6 
 7     printf("protocol: %s\n",protocol);
 8     printf("host: %s\n",host);
 9     printf("port: %s\n",port);

应用

落谷——P1957 口算练习题

#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>

using namespace std;

void fun(char s, int a, int b) {
    
    
	char buf[100];
	memset(buf, 0, sizeof(buf));
	switch (s)
		{
    
    
			case 'a':
			
			//	cout << sum<<endl;
				sprintf_s(buf, "%d+%d=%d", a, b, a + b);
				break;
			case 'b':
						//	cout << sum << endl;
				sprintf_s(buf, "%d-%d=%d", a, b, a - b);
				break;
			case 'c':
						//	cout << sum << endl;
				sprintf_s(buf, "%d*%d=%d", a, b, a * b);
				break;
			default:
				break;
		}
	cout << buf << endl << strlen(buf) << endl;
}

int main() {
    
    
	int num;
	cin >> num;
	char x= ' ';
	while (num--) {
    
    
		int sum;
		char s[10];
		cin >> s;
		int a, b;
		if (s[0] >= 'a' && s[0] <= 'c') {
    
    
			cin >> a >> b;
			fun(s[0], a, b);
			x = s[0];
		}
		else {
    
    
			sscanf_s(s, "%d", &a);
		//	cout << a;
			cin >> b;
			fun(x, a, b);
		}
		
		
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_64632836/article/details/127756617
今日推荐