我将char *转换为char **。每个单词必须折叠到数组。但只折叠第一个字。 输入:“abc def 123” out(预期):num == 3,arr == {“abc”,“def”,“123”} out(real):num == 1,arr == {“abc”}
struct CommandArray
{
vector<char*> Arr;
USHORT Num;
};
CommandArray Text::StrToArray(LPSTR Str)
{
CommandArray Out;
LPSTR TempStr;
Out.Num = 0;
TempStr = strtok (Str," ");
while(TempStr != NULL)
{
Out.Arr.push_back(TempStr);
Out.Num++;
TempStr = strtok(NULL," ");
}
return Out;
}
答案 0 :(得分:0)
strtok
修改了它的第一个参数(这就是为什么它是char*
而不是char const*
)。一个猜测是,在调用Text::StrToArray
之后你也会这样做。
答案 1 :(得分:0)
首先。使用cin.getline(input,32);
获取以空格分隔的输入,cin>>input
将无效。
关于char*
到char**
。下面的代码将每个单词折叠成一个数组。
#include<windows.h>
#include<vector>
#include<string>
#include<iostream>
using namespace std;
struct CommandArray
{
vector<char*> Arr;
USHORT Num;
};
CommandArray StrToArray(LPSTR Str)
{
CommandArray Out;
LPSTR TempStr;
Out.Num = 0;
TempStr = strtok (Str," ");
while(TempStr != NULL)
{
Out.Arr.push_back(TempStr);
Out.Num++;
TempStr = strtok(NULL," ");
}
return Out;
}
int main()
{
int ROWS=80; //80 characters wide
int COLUMNS=20;// 20 lines
int i;
char seperators[] = " ,\t\n";
char *token;
char* input_Dynamic1DCharPointerArray = new char[80];
char **output_Dynamic2DCharPointerArray = 0;
//memory allocated for elements of rows.
output_Dynamic2DCharPointerArray = new char *[ROWS] ;
//memory allocated for elements of each column.
for( i = 0 ; i < ROWS ; i++ ) output_Dynamic2DCharPointerArray[i] = new char[COLUMNS];
strcpy(input_Dynamic1DCharPointerArray,"apples 123 oranges 456 bananas 789 lemons 101112" );
//cout<<" \n";
//cin.getline(input_Dynamic1DCharPointerArray,32);
cout<<" \ninput = "<<input_Dynamic1DCharPointerArray<<" \n\n";
cout<<"Output = \n";
token = strtok( input_Dynamic1DCharPointerArray, seperators );
i=0;
while( token != NULL )
{
strcpy(output_Dynamic2DCharPointerArray[i],token);
cout<<output_Dynamic2DCharPointerArray[i]<<" \n";
token = strtok( NULL, seperators ); // C4996
i++;
}
cout<<" \n";
delete[] input_Dynamic1DCharPointerArray;
//free the allocated memory
for( i = 0 ; i < ROWS ; i++ )
delete [] output_Dynamic2DCharPointerArray[i] ;
delete [] output_Dynamic2DCharPointerArray ;
return 0;
}