简体   繁体   中英

Failure when using strtok_r function

Please help me fix the this code. I am lost with strtok function now. I get message "ISO C++ forbids comparison between pointer and integer" about the line "if (tokens[0] == "A")"

if (started && ended)
{


  char *p = inData;
  char *tokens[50];
  int i = 0;

  while (i < 50) {
    tokens[i] = strtok_r(p,",",&p);
    if (tokens[i] == NULL) {
      break;
    }
    i++;
  }


  if (tokens[0] == 'A'){
    pinMode(atoi(tokens[1]),OUTPUT);       
    analogWrite(atoi(tokens[1]),atoi(tokens[2]));
  }

  else if (tokens[0] == 'D')
  {
   if (atoi(tokens[2]) == 1)
   {
     pinMode(atoi(tokens[1]),OUTPUT);
     digitalWrite(atoi(tokens[1]),HIGH);
   }
   else if (atoi(tokens[2]) == 0)
   {
     pinMode (atoi(tokens[1]),OUTPUT);
     digitalWrite(atoi(tokens[1]),LOW);
   }       
 }



  started = false;
  ended = false;
  index = 0; 
}

In the line if (tokens[0] == 'A') , the character constant 'A' is simply the ASCII value of A - 65 or 0x41, while tokens[0] is a char * . Hence you have a "comparison between pointer and integer".

What is it that you mean to do? To check whether the first character of the token is a capital A, write

if (tokens[0][0] == 'A')

To check whether it is the string "A", write

if (strcmp(tokens[0], "A") == 0)

Also, your use of strtok_r is wrong. You are using the input buffer to store context information and so overwriting it. (Is there really a reason you need to use the reentrant version? The standard strtok doesn't require context storage.) It should look like

char *token;
char *context;

for (token = strtok(p, ",", &context);
    token;
    token = strtok(NULL, ",", &context)) {

  tokens[i++] = token;
  if (i >= 50) break;
}

In addition you are better off using strsep in place of strtok like this

char *token;
while (token = strsep(&p, ",")) {
  tokens[i++] token;
  if (i >= 50) break;
}

You say that the error occurs on the line

if (tokens[0] == "A")

yet there is no such line in the code that you show us.

I assume you actually meant the following:

if (tokens[0] == 'A')

The reason the above won't work is that tokens[0] is of type char* , and you can't compare a char* to a char like this. You need a string comparison if you want to compare the two strings for equality:

if (strcmp(tokens[0], "A") == 0)

Well, that line (which I couldn't find in your code) is really wrong. tokens[0] is a char* , and 'A' is char . If you want to compare the all string, use strcmp . If you want to check the first char of tokens[0] , use tokens[0][0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM