Mình có viết một hàm GetTokens() chỉ lấy 1 hoặc 2 tokens bằng C. Bây giờ mình muốn đổi sang C++ và sử dụng vector để lưu giá trị 2 tokens đó. Mình muốn hàm GetTokens() trả về một con trỏ tới vector nhưng mình không chắc lắm. Mấy bạn có cho mình ý kiến với.
Đây là header của mình:
#ifndef Tokenizer_h
#define Tokenizer_h
#include <vector>
using namespace std;
class Tokenizer {
public:
is_number(char *arr);
vector<string>* GetTokens();
};
#endif
Còn đây là hàm GetTokens
#include <vector>
#include <stdlib.h>
#include <strings.h>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <iostream>
#include <string>
#include "Tokenizer.hpp"
using namespace std;
int is_number(char *arr){
int check = 0;
for (int i= 0; i < strlen(arr); i++){
if (isdigit(arr[i])){
//check = 0; //number
} else check++;//string
//*arr++;
}
if (check == 0)
return 0;//number
else
return 1; //string
}
vector<string>* GetTokens()
{
vector<string> *ptrVT = new vector<string>();;
int countVT = 0;
char str[256];
char *ptr;
char *ptr2;
char **b = (char **)malloc(256*sizeof(char));
char *p;
int count =0;
int index;
int j =0;
int num_space;
int checkNumCL = 0;
do{
do{
count = 0;
index = 0;
num_space = 0;
countVT =0;
/*if (checkNumCL > numCL)
{
exit(0);
}*/
//stdin_flush();
cout << "> " ;
fgets(str,66,stdin);
str[strlen(str)-1] = '\0';
if (strlen(str)>20){
cout << "ERROR! Input string too long." << endl;
//checkNumCL++ ;
continue;
}
ptr = str;
while (*ptr != '\0'){
if (*ptr == ' '){
num_space++;
}
ptr++;
}
p = strtok(str," ");
while (p != NULL){
b[index] = p;
ptrVT->push_back(&p[index]);
count++;
index++;
countVT++;
p = strtok(NULL," ");
}
if (count > 2 || count <= 0){
cout << "ERROR! Incorrect number of tokens found." << endl;
//checkNumCL++ ;
}
ptr = str;
}while(count > 2 || count <= 0);
if (count == 2){
char temp[256] = {};
for (int i=0; i < count; i++){
if (is_number(b[i]) == 0)//number
strcat(temp,"INT");
else
strcat(temp,"STR");
}
if (strcasecmp(temp,"STRINT")!= 0){
cout << "ERROR! Expected STR INT." << endl;
//checkNumCL++ ;
continue;
}
}
else if(count == 1)
{
if(is_number(b[0]) == 0){
cout << "ERROR! Expected STR." << endl;
//checkNumCL++ ;
continue;
}
}
if (strcasecmp(str,"quit") == 0){
exit(0);
}
j = 0;
while (j < index){
if (is_number(b[j]) == 0)
cout << "INT ";
else
cout << "STR ";
j++;
}
checkNumCL++;
printf("\n");
}while(strcasecmp(str,"quit\n") != 0); //&& checkNumCL < numCL);
return ptrVT;
}