首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

cstring类型怎么取出赋值给数组

2013-06-26 
cstring类型如何取出赋值给数组现有CString str0.513 0.618 0.324 0.465 -0.453 如何将str里面的数值

cstring类型如何取出赋值给数组
现有CString str=="0.513 0.618 0.324 0.465 -0.453 ";如何将str里面的数值取出来分别存入一个数组a[]中呢?谢谢 cstring
[解决办法]
字符串中各个子字符串是用" "分隔开来的是吧?
可以采用Cstring查找子串功能或者是std::string的字串查找功能实现,一步一步的拆分即可实现。
下面是我在linux下通过std::string的字串查找的实现拆分,可以参考:


#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<dirent.h>
#include<errno.h>
#include<string>
#include<iostream>
using namespace std;

int main()
{
    std::string source("0.513 0.618 0.324 0.465 -0.453 ");
    double a[5] = {0.0};
    std::size_t pos = 0;
    std::string curStr;
    int cout = 0;
    do {
        pos = source.find_first_of(" ");
        if (string::npos == pos)
            break;
        curStr = source.substr(0, pos);
        a[cout++] = atof(curStr.c_str());
        source = source.substr(pos+1, source.length() - curStr.length() - 1);
    } while (true);

    for (int i=0; i<cout; i++) {
       printf("%lf ", a[i]);
    }
    printf("\n");
}

热点排行