- 1、sscanf
- 2、stringstream
在算法竞赛中,sscanf和stringstream一般配合getline()使用,可以更灵活地读取数据 1、sscanf
使用的头文件:
#include
#include
#include
使用样例:
假设我们读入一行字符串"a b c",需要分别取出a,b,c
#define _CRT_SECURE_NO_DEPRECATE
#include
#include
#include
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",
结果如下
使用的头文件:
#include
#include
#include
使用样例:
假设我们读入一行字符串"a b c",需要分别取出a,b,c
#define _CRT_SECURE_NO_DEPRECATE
#include
#include
#include
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
#include
#include
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条)