Home  >  Q&A  >  body text

c++ string转化为int数组

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

黄舟黄舟2764 days ago519

reply all(3)I'll reply

  • 高洛峰

    高洛峰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);
    }

    reply
    0
  • 巴扎黑

    巴扎黑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

    reply
    0
  • ringa_lee

    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);
      }

    reply
    0
  • Cancelreply