所以我在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;
}
答案 0 :(得分:2)
以下程序显示了如何更改与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