给出一个字符串作为输入,该输入由数字组成,我想将其转换为C ++中的整数数组。
#include <string>
#include <iostream>
#include <sstream>
using std::string;
using std::stringstream;
using std::cout;
using std::endl;
int main(int argc,char** argv) {
string num="-24 2 90 24 50 76";
stringstream stream(num);
while(stream){
int n;
stream>>n;
cout<<n<<endl;
}
return 0;
}
输出(GCC)
-24 2 90 24 50 76 76
为什么我会获得额外的价值,将它们转换为整数数组的效率如何?
更新:
What if the string stream contains delimiter other than space, How to parse this?
For eg:
string num="-24,2,90,24,50,76";