C++ 如何将CString拆分为字符?

C++ 如何将CString拆分为字符?,c++,mfc,C++,Mfc,我有这样的想法: "0 2 8 27 29 32 35 48 52 55 58 62 72" 我需要把每个数字放在数组的一个单独的元素中。 有人能帮我吗? -ThanX我假设您希望这些数字是整数数组。使用std::vector可能更好 std::vector<int> oResult; CString oMyStr = _T("0 2 8 27 29 32 35 48 52 55 58 62 72"); int iIndex = 0; CString oToken = oMyStr

我有这样的想法: "0 2 8 27 29 32 35 48 52 55 58 62 72" 我需要把每个数字放在数组的一个单独的元素中。 有人能帮我吗?
-ThanX

我假设您希望这些数字是整数数组。使用std::vector可能更好

std::vector<int> oResult;
CString oMyStr = _T("0 2 8 27 29 32 35 48 52 55 58 62 72");

int iIndex = 0;
CString oToken = oMyStr.Tokenize(_T(" "), iIndex); // Tokenize with space

while ( !oToken.IsEmpty() )
{
    try
    {
        int iNbr = atoi( oToken );
        oResult.push_back(iNbr);
    }
    catch (...) { } // This is bad code, but I'm just lazy.

    oToken = oMyStr.Tokenize(_T(" "), iIndex); // Tokenize with space
}

但是,如果向量为空,则可能会崩溃。

使用以下代码将各个元素分隔为字符串向量,其中每个元素都作为单独的元素

#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

vector<string> &split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

int main()
{
    string s = "0 2 8 27 29 32 35 48 52 55 58 62 72";
    vector<string> elemsVec = split(s, ' ');
    vector<string>::iterator it;
    for(it = elemsVec.begin(); it != elemsVec.end(); ++it)
        cout << *it << " ";

    return 0;
}
#包括
#包括
#包括
使用名称空间std;
向量和拆分(常量字符串和字符串、字符、向量和元素){
溪流ss(s);;
字符串项;
while(getline(ss、item、delim)){
元素推回(项目);
}
返回元素;
}
向量拆分(常量字符串和s、字符delim){
向量元素;
拆分(s、delim、elems);
返回元素;
}
int main()
{
字符串s=“0 2 8 27 29 32 35 48 52 55 58 62 72”;
向量elemsVec=拆分(s',);
向量::迭代器;
for(it=elemsVec.begin();it!=elemsVec.end();++it)

你没试过什么吗?不确定是糟糕的问题还是糟糕的英语…你的意思是你想要13个不同的数组?这些数组的类型是什么?我建议查看
CString
类,看看是否有任何子字符串、查找或解析方法。提取数字,然后将其转换为.Int数组或CString数组?然后执行以下操作它真的必须是一个数组。向量在C++中更有用。@ SimoErkinheimo int数组会更好。它是家庭作业的一部分,如果我不使用向量(我们的老师以前从来没有使用过),那就更好了。-thnks谢谢你的帮助Thnk you bro,但是我在使用MFC,我还能使用它们吗?你对Java的接触太多了,以至于无法保持健康。放弃try-catch处理程序,它不会做任何有用的事情。唯一会引发异常的操作是
oResult。向后推
。如果内存不足,不要默默忽略它。H让应用程序终止,或者让下游异常处理程序处理它。
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

vector<string> &split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

int main()
{
    string s = "0 2 8 27 29 32 35 48 52 55 58 62 72";
    vector<string> elemsVec = split(s, ' ');
    vector<string>::iterator it;
    for(it = elemsVec.begin(); it != elemsVec.end(); ++it)
        cout << *it << " ";

    return 0;
}