c++ string转化为int数组
黄舟
黄舟 2017-04-17 13:15:21
[C++讨论组]

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

黄舟
黄舟

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

全部回复(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) {}

希望有帮助

ringa_lee

一种比较愚钝的方法,如果是我自己我会采用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);
  }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号