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

标签 c++ stringstream

所以我正在用 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; 
}

最佳答案

下面的程序展示了如何更改与stringstream关联的string并从新的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

关于c++ - 如何在 C++ 中重用字符串流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33840391/

相关文章:

c++ - 从组件构造字符串的最佳方法,iostream 样式

c++ - stringstream 清除后不接受任何数据

c++ - QByteArray 到 char*,用 libcurl 发送

c++ - 类模板上的运算符重载

c++ - 从 void* 转换为 C++ 中的对象数组

c++ - C++ getline添加空格

c++ - 如何使字符串 vector 在用户输入中保留空格?

c++ - 在第一个参数上部分特化模板

c++ - 创建行为类似于 stringstream 的类的最简单方法

c++ - 如何将二进制文件的十六进制表示形式保存到 std::string 中?