C++ 使用strtok和数组时出错

C++ 使用strtok和数组时出错,c++,strtok,C++,Strtok,我试图使用strtok和strncpy拆分字符串并将结果放入数组,但当代码运行时,它会抛出一个错误 代码段: #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string.h> using namespace std; int main() { char str[] ="( 6 + 2 )"; char *pch; int

我试图使用
strtok
strncpy
拆分字符串并将结果放入数组,但当代码运行时,它会抛出一个错误

代码段:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>

using namespace std;

int main() 
{    
    char str[] ="( 6 + 2 )";
    char *pch;
    int i = 0;

    pch = strtok(str, " ");  

    while (pch != NULL)
    {
         printf("%s\n", pch);     
         pch = strtok (NULL, " ");  
         i = i + 1;
    }

    char arreglo[i];

    strncpy(arreglo, pch, sizeof(arreglo));

    cin.get();
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{    
字符str[]=“(6+2)”;
char*pch;
int i=0;
pch=strtok(str,“”);
while(pch!=NULL)
{
printf(“%s\n”,pch);
pch=strtok(空,“”);
i=i+1;
}
char arreglo[i];
strncpy(arreglo,pch,sizeof(arreglo));
cin.get();
}
有人能告诉我我做错了什么,或者如何修复它吗

strncpy( arreglo, pch, sizeof(arreglo) );
此语句给出了一个分段错误,因为
pch
NULL

此代码段

char arreglo[i];

strncpy( arreglo, pch, sizeof(arreglo) );
毫无意义

首先,C++中没有可变长度数组。因此,最好不要使用编译器的这种扩展

第二,退出前一个循环后,
pch
等于NULL。而且这个声明

strncpy( arreglo, pch, sizeof(arreglo) );
不做你想做的事

我想你的意思是这样的

#include <vector>
#include <string>

//...

std::vector<std::string> v;

pch = strtok( str, " " );  

while ( pch != NULL )
{
         printf ("%s\n",pch);     
         v.push_back( pch );
         pch = strtok( NULL, " " );  
}
#包括
#包括
//...
std::向量v;
pch=strtok(str,“”);
while(pch!=NULL)
{
printf(“%s\n”,pch);
v、 推回(pch);
pch=strtok(空,“”);
}

strncpy(arreglo,pch,sizeof(arreglo))中您到底想做什么。您遇到了什么错误?乍一看,您希望在编译过程中执行一半的代码。我试图将字符串(6+2)划分为一个数组,如:arreglo[0]=(,arreglo[1]=6,…,函数strtok将(6+2)划分为(,6,+,2,)所以我假设用StnPy我可以做到这一点,但是我不能GYG,错误是控制台停止工作,你使用40年的技术出错了。为什么不是C++标准库,几乎20年前发明的?为什么当你不使用C++的任何特性时,把它标记为C++?分段错误。