gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:19:10 24 4
gpt4 key购买 nike

所以我在 C++ 中试验 stringstream,我想知道为什么 input3 保持不变。如果我输入:“test”、“testing”、“tester”,input1、input2、input3都会分别有对应的字符串变量。但是当我重新输入值时,让我们只说“测试”和“测试”,“测试器”变量仍然在前一个输入的流中。我该如何清除它?任何帮助将不胜感激。谢谢!

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com