C++怎么将string类型转为数组
string类型怎么转为BYTE数组我要去掉空格,然后每两个字符为一个串转成数组,并将16进制转为10进制;
如:
string str="FF FF FF FF FF FF FF FF";
转为:
BYTE byte[8];
byte[0]={255};
byte[0]={255};
...
byte[7]={255};
#include <iostream> #include <string> #include <vector> #include <sstream> #include <limits> #include <exception> std::vector<unsigned char> foo( const std::string& str ) { std::vector<unsigned char> ret; std::istringstream is( str ); for( int val; is>>std::hex>>val; ) { if( val<std::numeric_limits<unsigned char>::min() || val>std::numeric_limits<unsigned char>::max() ) throw std::domain_error( "fuck" ); ret.push_back( val ); } if( !(is>>std::ws).eof() ) throw std::domain_error( "shit" ); return ret; } int main( void ) { try { std::vector<unsigned char> arr = foo( "FF FF FF FF FF FF FF FF" ); for( size_t i=0; i!=arr.size(); ++i ) std::cout << (int)arr[i] << ' '; } catch( std::exception& e ) { std::cerr << e.what() << '\n'; return 1; } }