簡體   English   中英

如何在 C++ 中重用字符串流?

[英]How to reuse a stringstream in C++?

所以我正在 C++ 中試驗 stringstream,我想知道為什么 input3 保持不變。 如果我輸入:“test”、“testing”和“tester”,則 input1、input2 和 input3 都會分別有它們對應的字符串變量。 但是,當我重新輸入值時,只說“test”和“testing”,“tester”變量仍將在前一個輸入的流中。 我如何清除它? 任何幫助將不勝感激。 謝謝!

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

int main(){
    std::string input, input1, input2, input3;
    std::string x, y, z;
    std::string other;
    std::getline(std::cin, input);
    std::istringstream getter{input};
    getter >> input1 >> input2 >> input3;
    while (input1 != "break"){
        if (input1 == "test"){
            function(input2, input3);
            std::getline(std::cin, other); //receive more input
            getter.str(other);
            getter >> x >> y >> z; //get new data
            input1 = x; input2 = y; input3 = z; //check against while loop
        }

        else{
            std::cout << "WRONG!" << std::endl;
            std::getline(std::cin, input);
            getter >> input1 >> input2 >> input3;

        } 
    }
    return 0; 
}

下面顯示了程序如何改變string與相關stringstream從新提取數據string

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

int main()
{
   std::string input1 = "1 2";
   std::string input2 = "10 20";

   std::istringstream iss{input1};
   int v1 = 0, v2 = 0;

   // Read everything from the stream.
   iss >> v1 >> v2;
   std::cout << "v1: " << v1;
   std::cout << ", v2: " << v2 << std::endl;

   // Reset the string associated with stream.
   iss.str(input2);

   // Expected to fail. The position of the stream is
   // not automatically reset to the begining of the string.
   if ( iss >> v1 >> v2 )
   {
      std::cout << "Should not come here.\n";
   }
   else
   {
      std::cout << "Failed, as expected.\n";

      // Clear the stream
      iss.clear();

      // Reset its position.
      iss.seekg(0);

      // Try reading again.
      // It whould succeed.
      if ( iss >> v1 >> v2 )
      {
         std::cout << "v1: " << v1;
         std::cout << ", v2: " << v2 << std::endl;
      }
   }

   return 0;
}

輸出,在 Linux 上使用 g++ 4.8.4:

v1: 1, v2: 2
Failed, as expected.
v1: 10, v2: 20

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM