0
点赞
收藏
分享

微信扫一扫

(C++)sscanf和stringstream的使用样例

戴老师成长记录仪 2022-03-30 阅读 74
c++算法

sscanf和stringstream的使用样例


在算法竞赛中,sscanf和stringstream一般配合getline()使用,可以更灵活地读取数据

1、sscanf

使用的头文件:

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

使用样例:
假设我们读入一行字符串"a b c",需要分别取出a,b,c

#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;

int main()
{
	int a, b, c;
	string str;

	//使用getline()读入数据
	getline(cin, str);

	//使用sscanf读入a,b,c
	sscanf(str.c_str(), "%d %d %d", &a, &b, &c);

	//分别输出a,b,c
	cout << "a: " << a << '\n' << "b: " << b << '\n' << "c: " << c;
	return 0;
}

我们读入的字符串为"123 456 789",
结果如下
在这里插入图片描述

2、stringstream

使用的头文件:

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

使用样例:
假设我们读入一行字符串"a b c",需要分别取出a,b,c

#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<cstdio>
#include<sstream>
using namespace std;

int main()
{
	int a, b, c;
	string str;

	//使用getline()读入数据
	getline(cin, str);

	//使用stringstream读入a,b,c
	stringstream ssin(str);
	ssin >> a;
	ssin >> b;
	ssin >> c;

	//分别输出a,b,c
	cout << "a: " << a << '\n' << "b: " << b << '\n' << "c: " << c;
	return 0;
}

我们读入的字符串为"123 456 789",
结果如下
在这里插入图片描述
也可以使用数组存a,b,c

#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<cstdio>
#include<sstream>
using namespace std;

int main()
{
	int num[3], i = 0;
	string str;

	//使用getline()读入数据
	getline(cin, str);

	//使用stringstream读入a,b,c
	stringstream ssin(str);
	while (ssin >> num[i])i++;

	//分别输出a,b,c
	cout << "a: " << num[0] << '\n' << "b: " << num[1] << '\n' << "c: " << num[2];
	return 0;
}

结果相同
在这里插入图片描述

举报

相关推荐

0 条评论