问题描述
例如 现在有个字符串s='12 23 34'中间都是空格隔开的 我想把每个值都保存的int数组中 thanks
问题解答
回答1:http://stackoverflow.com/questions/236129/split-a-string-in-cstring到int, 就是atoi, 或者sscanf, 或者stringstream也可以上面的解决方案是广谱的. 就是分割单个解决.
闲的蛋疼, 写一个C语言版本的. stringstream虽然写起来容易, 但是我不用, 效率比较低.....
const char* s = '1 2 3';int32_t value = 0;char* line = NULL, *ptr = NULL;line = strtok_r(const_cast<char*>(s, ' ', &ptr));while (line) { if (sscanf(line, '%d', &value) >= 1) (void)value;//这边就是1,2,3之类的 line = strtok_r(NULL, ',', &ptr);}回答2:
const size_t SIZE = 10;int * array = new int[SIZE];std::istringstream stringStream('12 34 44');for (size_t i = 0; (i < SIZE) && (stringStream >> array[i]); ++i) {}
希望有帮助
回答3:一种比较愚钝的方法,如果是我自己我会采用stringstream来进行转化。
char x[10]; int a[10]; std::string name = '12 3 4 56'; const char * s = name.c_str(); const char * s1 = name.c_str(); int i=0; while(s-s1<name.length() && sscanf(s, '%s', x)){ s += strlen(x)+1; a[i++] = atoi(x); }