高洛峰2017-04-17 13:17:21
http://stackoverflow.com/questions/236129/split-a-string-in-c
String to int, that is atoi, or sscanf, or stringstream can also be used
The above solution is wide Spectral. It is divided into individual solutions.
I feel so free to write a C language version. Although stringstream is easy to write, I don’t use it and the efficiency is relatively low...
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);
}
巴扎黑2017-04-17 13:17:21
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) {}
Hope this helps
ringa_lee2017-04-17 13:17:21
A relatively stupid method. If it were me, I would use stringstream for conversion.
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);
}