sstream头文件

sstream头文件之前的sscanf和sprintfsscanf函数原型为intsscanf(constchar*str,constchar*format,…),将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内;#include<iostream>#include<cstdio>usingnamespacestd;i…

大家好,又见面了,我是你们的朋友全栈君。

之前的sscanf和sprintf
sscanf函数原型为int sscanf(const char *str,const char *format,…),将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内;

#include <iostream>
#include <cstdio>
using namespace std;

int main(){ 
   
	char s[] = "123.432,432";
	double f1;
	int f2;
	int n;
	sscanf_s(s, "%lf,%d%n", &f1, &f2, &n);
	cout << f1 << " " << f2 << " " << n << endl;

	system("pause");
	return 0;
}

sstream头文件
sprintf函数原型为 int sprintf(char *str, const char *format, …),作用是格式化字符串;

void sprintf() { 
   
	char str[256] = { 
    0 };
	int data = 1024;
	//将data转换为字符串
	sprintf_s(str, "%d", data);
	cout << str << endl;

	//获取data的十六进制
	sprintf_s(str, "0x%X", data);
	cout << str << endl;

	//获取data的八进制
	sprintf_s(str, "0%o", data);
	cout << str << endl;

	const char *s1 = "Hello";
	const char *s2 = "World";
	//连接字符串s1和s2
	sprintf_s(str, "%s %s", s1, s2);
	cout << str << endl;
}

sstream头文件
sstream
sstream定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作

  • 可以将内容写入其中,和cout一样
stringstream ss;
    double price = 380.0;
    char *ps = " for a copy of the ISO/EIC C++ standard!";
    ss.precision(2);//精度
    ss << fixed;//固定位数
    ss << "Pay only CHF " << price << ps << endl;
    cout << ss.str() << endl;//将缓冲区的内容转化为字符串
  • 它可以拼接字符串(不同数据类型)
  • 可以从中读取数据,和cin一样:
string word;
while(ss>>word){ 
   
    cout << word << endl;
    }
  • 利用stringstream可以轻松完成字符串和基本数据类型的相互转换
	string s = "12345";
	stringstream ss;
	int x;
	ss << s;
	ss >> x;
	cout << x << endl;
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/136123.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号