字符串流(stringstream)

标准头文件 <sstream> 定义了一个叫做 stringstream 的类,使用这个类可以对基于字符串的对象进行像流(stream)一样的操作。这样,我们可以对字符串进行抽取和插入操作,这对将字符串与数值互相转换非常有用。例如:将一个字符串转换为一个整数,可以这样写:

#include <iostream>
#include <string>
#include <sstream>

   string mystr("67");
   int myint;
   stringstream(mystr)>>myint;  //vs2010貌似不是很支持这样,改了项目属性-清单-输入输出-嵌入清单->否,成功。

   cout<<myint<<endl;

这个例子中先定义了一个字符串类型的对象mystr,初始值为"67",又定义了一个整数变量myint。然后我们使用 stringstream 类的构造函数定义了这个类的对象,并以字符串变量mystr为参数。因为我们可以像使用流一样使用stringstream 的对象,所以我们可以像使用cin那样使用操作符 >> 后面跟一个整数变量来进行提取整数数据。这段代码执行之后变量 myint 存储的是数值 67

#include <iostream>
#include <string>
#include <sstream>

string mys;
float price;
int quality;
cout<<"Please input the price :";
getline(cin,mys);
stringstream(mys)>>price;
cout<<"Please input the number :";
getline(cin,mys);
stringstream(mys)>>quality;
cout<<"The total price is :"<<price*quality<<endl;

在这个例子中,我们要求用户输入数值,但不同于从标准输入中直接读取数值,我们使用函数getline从标注输入流cin中读取字符串对象(mystr),然后再从这个字符串对象中提取数值price和quantity。

通过使用这种方法,我们可以对用户的输入有更多的控制,因为它将用户输入与对输入的解释分离,只要求用户输入整行的内容,然后再对用户输入的内容进行检验操作。这种做法在用户输入比较集中的程序中是非常推荐使用的。

原文地址:https://www.cnblogs.com/guozqzzu/p/3588730.html