如何在c ++中将字符串解析为多个类型?

tem*_*emo 2 c++ string parsing c++11

cin >> *integerVar >> *charVar;可以正确读取"25 b"之类的输入.使用现有字符串执行此操作的最简单方法是什么(我可以通过拆分然后解析每个部分来手动完成,但更好的方法是什么)?

Ste*_*ner 6

使用istringstream类似的,例如:

#include <string>
#include <sstream>

int main(void)
{
    std::istringstream ss("25 b");
    int x; std::string bstr;

    ss >> x >> bstr;

    return 0;
}

// note that std:istringstream allows ss >> x, but not ss << "some value".
// if you want to support both reading and writing, use a stringstream (which would then support ss >> x as well as ss << "some value")
Run Code Online (Sandbox Code Playgroud)


Pau*_*ans 5

使用std::stringstream:

std::stringstream myStr{"25 b"};
myStr >> *integerVar >> *charVar;
Run Code Online (Sandbox Code Playgroud)