I used strtok
to tokenize a string. But many developers said me to avoid strtok
, why? How should I optimize this code? Is it really wrong that I used strtok
? If so then with what should I replace it?
DWORD FN_attack_speed_from_file(const char *file)
{
FILE *fp = fopen(file, "r");
if(NULL == fp)
{
return 0;
}
int speed = 1000;
const char *key = "DirectInputTime";
const char *delim = " \t\r\n";
const char *field, *value;
char buf[1024];
while(fgets(buf, 1024, fp))
{
field = strtok(buf, delim);
value = strtok(NULL, delim);
if(field && value)
{
if(0 == strcasecmp(field, key))
{
float f_speed = strtof(value, NULL);
speed = (int)(f_speed * 1000.0);
break;
}
}
}
fclose(fp);
return speed;
}
I would like to modernize this as C++, and learn modern coding.
strtok
is a valid function in C++. It's not wrong to use it in C++, it's not necessarily that much faster or slower. But your C++ code will look better if you avoidstrtok
. If you want to move to C++ then it's more important to usestd::fstream
,std::getline
andstd::string
which have significant advantage over their C counterpart, you would end up avoidingstrtok
as well. – Barmak Shemirani 2 days ago