c++ string转化为int数组
黄舟
黄舟 2017-04-17 13:15:21
0
3
549

例如 现在有个字符串s="12 23 34"中间都是空格隔开的 我想把每个值都保存的int数组中
thanks

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
小葫芦

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);
}
巴扎黑
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

左手右手慢动作

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);
  }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template