code

stringstream은 정확히 무엇을합니까?

codestyles 2020. 9. 7. 08:09
반응형

stringstream은 정확히 무엇을합니까?


저는 어제부터 C ++를 배우려고 노력하고 있으며이 문서를 사용하고 있습니다 : http://www.cplusplus.com/files/tutorial.pdf (page 32). 문서에서 코드를 찾아 실행했습니다. 가격은 Rs 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 명령은 정확히 무엇을합니까? 문서에서 인용 :

"이 예에서는 표준 입력에서 간접적으로 숫자 값을 얻습니다. 표준 입력에서 직접 숫자 값을 추출하는 대신 표준 입력 (cin)에서 문자열 객체 (mystr)로 줄을 가져온 다음 정수를 추출합니다. 이 문자열의 값을 int (수량) 유형의 변수로 변환합니다. "

내 인상은 함수가 문자열의 필수 부분을 취하여 입력으로 사용한다는 것입니다.

(여기에서 질문하는 방법을 정확히 모르겠습니다. 저도 프로그래밍이 처음입니다.) 감사합니다.


때때로 stringstream을 사용하여 문자열과 다른 숫자 유형간에 변환하는 것이 매우 편리합니다. 의 사용법은의 사용법과 stringstream유사 iostream하므로 배우는 데 부담이되지 않습니다.

Stringstreams는 문자열을 읽고 데이터를 문자열에 쓰는 데 사용할 수 있습니다. 주로 문자열 버퍼로 작동하지만 실제 I / O 채널은 없습니다.

stringstream 클래스의 기본 멤버 함수는 다음과 같습니다.

  • str(), 버퍼의 내용을 문자열 유형으로 반환합니다.

  • str(string), 버퍼의 내용을 문자열 인수로 설정합니다.

다음은 문자열 스트림을 사용하는 방법의 예입니다.

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

결과는 dec: 15 hex: f입니다.

istringstream 거의 동일하게 사용됩니다.

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

FYI, the inheritance relationships between the classes are:

string stream classes


To answer the question. stringstream basically allows you to treat a string object like a stream, and use all stream functions and operators on it.

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

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

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 stringstream object ss, modify its flags, put a number into it with operator<<, and extract it via str(). I guess that operator>> could be used.

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

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


From C++ Primer:

The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

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

case 1

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

Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

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

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

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.


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

You then tried to convert the first token (blank delimited) into an 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.

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

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

참고URL : https://stackoverflow.com/questions/20594520/what-exactly-does-stringstream-do

반응형