int
const
);
它强大的功能体现在对format的支持,以及类型转换上。
注:{a|b|c}表示a,b,c中选一,[d],表示可以有d也可以没有d。
width:宽度,一般可以忽略,用法如:
const
char
sscanf(sourceStr,
cout
结果为:hello
{h
type
特别的:
%*[width]
const
char
sscanf(sourceStr,
cout
结果为:world
支持集合操作:
stringstream,顾名思义,就是字符串的输入输出流,跟fstream很相似。
需包含头文件:#include <sstream>
stringstream通常是用来做数据转换的。相比c库的转换,它更加安全,自动和直接。
例子一:基本数据类型转换例子 int转string
#include <string>
#include <sstream>
#include <iostream>
int main()
{
}
运行结果:print the string "1000"
例子二:除了基本类型的转换,也支持char *的转换。
#include <sstream>
#include <iostream>
int main()
{
}
屏幕显示 "8888"
例子三:再进行多次转换的时候,必须调用stringstream的成员函数clear().
#include <sstream>
#include <iostream>
int main()
{
}
运行clear的结果:
456
1
没有运行clear的结果:
456
8800090900
注意stringstream和sscanf的区别:
如果str[] = "one two three four";
如果按照这么读: char word[20][20]; for(i = 0; i < n; i++)sscanf(str, "%s", word[i]);
那么你读入的每一个word[i]都是单词"one",而用stringstream则是将这几个单词依次读入。
原因很简单,stringstream是对一个确定的字符串进行操作,内部有一个指针标记读到哪了,而sscanf则每次都是从头对str进行读入。
虽然在ACM中不推荐使用C++中的输入输出流,但小数据量的题目偶尔为之,还是能大大提高写代码的速度和准确率的。