读书人

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

发布时间: 2013-06-26 14:29:32 作者: rapoo

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

读书人网 >C++

热点推荐