C++ stringstream 到底做了什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20594520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:14:11  来源:igfitidea点击:

What exactly does stringstream do?

c++sstream

提问by richard.g

I am trying to learn C++ since yesterday and I am using this document:http://www.cplusplus.com/files/tutorial.pdf(page 32) . I found a code in the document and I ran it. I tried inputting Rs 5.5 for price and an integer for quantity and the output was 0. I tried inputting 5.5 and 6 and the output was correct.

我从昨天开始尝试学习 C++,我正在使用这个文档:http: //www.cplusplus.com/files/tutorial.pdf(page 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; 
}

Question: What exactly does the mystring command do? Quoting from the document:

问题: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)."

“在这个例子中,我们间接地从标准输入中获取数值。我们不是直接从标准输入中提取数值,而是从标准输入(cin)中获取行到一个字符串对象(mystr)中,然后我们提取整数将此字符串中的值转换为 int(数量)类型的变量。”

My impression was that the function will take the integral part of a string and use that as input.

我的印象是该函数将取字符串的组成部分并将其用作输入。

(I don't exactly know how to ask a question here. I am also new to programming) Thank you.

(我不知道如何在这里提问。我也是编程新手)谢谢。

回答by richard.g

Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstreamis similar to the usage of iostream, so it is not a burden to learn.

有时使用stringstream在字符串和其他数值类型之间进行转换是非常方便的。的用法和 的用法stringstream类似iostream,所以学习起来不是负担。

Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.

Stringstreams 可用于读取字符串和将数据写入字符串。它主要与字符串缓冲区一起工作,但没有真正的 I/O 通道。

The basic member functions of stringstream class are

stringstream 类的基本成员函数是

  • str(), which returns the contents of its buffer in string type.

  • str(string), which set the contents of the buffer to the string argument.

  • str(),它以字符串类型返回其缓冲区的内容。

  • str(string),它将缓冲区的内容设置为字符串参数。

Here is an example of how to use string streams.

以下是如何使用字符串流的示例。

ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;

The result is dec: 15 hex: f.

结果是dec: 15 hex: f

istringstreamis of more or less the same usage.

istringstream或多或少的用法相同。

To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.

总而言之,stringstream 是一种像独立 I/O 设备一样操作字符串的便捷方式。

FYI, the inheritance relationships between the classes are:

仅供参考,类之间的继承关系是:

string stream classes

字符串流类

回答by luk32

To answer the question. stringstreambasically allows you to treat a stringobject like a stream, and use all streamfunctions and operators on it.

要回答这个问题。stringstream基本上允许您将string对象视为 a stream,并stream在其上使用所有函数和运算符。

I saw it used mainly for the formatted output/input goodness.

我看到它主要用于格式化输出/输入优点。

One good example would be c++implementation of converting number to stream object.

一个很好的例子是c++将数字转换为流对象的实现。

Possible example:

可能的例子:

template <class T>
string num2str(const T& num, unsigned int prec = 12) {
    string ret;
    stringstream ss;
    ios_base::fmtflags ff = ss.flags();
    ff |= ios_base::floatfield;
    ff |= ios_base::fixed;
    ss.flags(ff);
    ss.precision(prec);
    ss << num;
    ret = ss.str();
    return ret;
};

Maybe it's a bit complicated but it is quite complex. You create stringstreamobject ss, modify its flags, put a number into it with operator<<, and extract it via str(). I guess that operator>>could be used.

也许它有点复杂,但它非常复杂。您创建stringstreamobject ss,修改其标志,使用 将数字放入其中operator<<,然后通过 提取它str()。估计operator>>可以用。

Also in this example the stringbuffer is hidden and not used explicitly. But it would be too long of a post to write about every possible aspect and use-case.

同样在这个例子中,string缓冲区是隐藏的,没有明确使用。但是写一篇关于每一个可能的方面和用例的文章会太长。

Note: I probably stole it from someone on SO and refined, but I don't have original author noted.

注意:我可能是从 SO 上的某个人那里偷来的并进行了改进,但我没有注意到原作者。

回答by jdhao

From C++ Primer:

C++ 入门

The istringstreamtype reads a string, ostringstreamwrites a string, and stringstreamreads and writes the string.

istringstream型读取一个字符串ostringstream写入字符串,以及字符串流读取和写入字符串

I come across some cases where it is both convenient and concise to use stringstream.

我遇到过一些使用stringstream既方便又简洁的情况。

case 1

情况1

It is from one of the solutionsfor this leetcode problem. It demonstrates a very suitable case where the use of stringstreamis efficient and concise.

这是从解决方案之一这个问题本文给出了。它演示了一个非常合适的案例,其中stringstream的使用高效而简洁。

Suppose aand bare complex numbers expressed in string format, we want to get the result of multiplication of aand balso in string format. The code is as follows:

假设ab在字符串格式表示的复数,我们想要得到的相乘的结果a,并b同时在字符串格式。代码如下:

string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;

int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of 
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;

out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';

// final result in string format
string result = out.str() 

case 2

案例2

It is also from a leetcode problemthat requires you to simplify the given path string, one of the solutions using stringstreamis the most elegant that I have seen:

也是来自leetcode 问题,需要你简化给定的路径字符串,使用 stringstream 的解决方案之一是我见过的最优雅的:

string simplifyPath(string path) {
    string res, tmp;
    vector<string> stk;
    stringstream ss(path);
    while(getline(ss,tmp,'/')) {
        if (tmp == "" or tmp == ".") continue;
        if (tmp == ".." and !stk.empty()) stk.pop_back();
        else if (tmp != "..") stk.push_back(tmp);
    }
    for(auto str : stk) res += "/"+str;
    return res.empty() ? "/" : res; 
 }

Without the use of stringstream, it would be difficult to write such concise code.

如果不使用stringstream,就很难写出如此简洁的代码。

回答by ilocos joe

You entered an alphanumeric and int, blank delimited in mystr.

您输入了一个字母数字和 int,以mystr.

You then tried to convert the first token (blank delimited) into an int.

然后,您尝试将第一个标记(空白分隔)转换为int.

The first token was RS which failed to convert to int, leaving a zero for myprice, and we all know what zero times anything yields.

第一个代币是 RS,它未能转换为int,为 myprice 留下零,我们都知道零乘以什么会产生什么收益。

When you only entered int values the second time, everything worked as you expected.

当您第二次只输入 int 值时,一切都按您的预期工作。

It was the spurious RS that caused your code to fail.

是虚假的 RS 导致您的代码失败。