我从昨天开始尝试学习 C++,我正在使用这个文档:http://www.cplusplus.com/files/tutorial.pdf (第 32 页)。我在文档中找到了一个代码并运行了它。我尝试输入 5.5 卢比的价格和一个整数作为数量,输出为 0。 我试过输入5.5和6,输出是正确的。
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string mystr;
float price = 0;
int quantity = 0;
cout << "Enter price: ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << "Enter quantity: ";
getline (cin,mystr);
stringstream(mystr) >> quantity;
cout << "Total price: " << price*quantity << endl;
return 0;
}
mystring 命令究竟做了什么?引用文档:
"In this example, we acquire numeric values from the standard input indirectly. Instead of extracting numeric values directly from the standard input, we get lines from the standard input (cin) into a string object (mystr), and then we extract the integer values from this string into a variable of type int (quantity)."
我的印象是该函数将获取字符串的一个组成部分并将其用作输入。
最佳答案
有时使用 stringstream 在字符串和其他数值类型之间进行转换非常方便。 stringstream
的用法和iostream
的用法差不多,学习起来不是负担。
Stringstreams 可用于读取字符串和将数据写入字符串。它主要与字符串缓冲区一起工作,但没有真正的 I/O channel 。
stringstream类的基本成员函数有
str()
,它以字符串类型返回其缓冲区的内容。str(string)
,将缓冲区的内容设置为字符串参数。
这是一个如何使用字符串流的示例。
ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;
结果是 dec: 15 hex: f
。
istringstream
的用法大致相同。
总而言之,stringstream 是一种像独立 I/O 设备一样操作字符串的便捷方式。
仅供引用,类之间的继承关系是:
关于c++ - stringstream 到底是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20594520/