1

I'm having trouble adding a "0" string to a list of strings in C.

With my current code, I'm having trouble distinguishing between a NULL value and a "0" with my current code. I have tried to debug with the if statement (if(pch == "0")) but when I'm outputting it doesn't go into the if statement.

          printf("%c\n",next_line[0]);
          pch = strtok(next_line,",");
          printf("%s\n",pch);
          if(pch == "0"){
            printf("NULL VALUE");
            strcpy(strs[i],pch);
            i++;
            pch = strtok(NULL, ",");
          }
          while(pch != NULL){
            strcpy(strs[i],pch);
            i++;
            pch = strtok(NULL, ",");
          }
          //go on to print values

the input is: 0,1,03:48:13,9 I never make it past the first character. What can I do to keep my code? Can I maybe change

     pch = strtok(NULL, ","); 
    to pch = strtok(SOMEOTHERVALUE, ",");? 
5
  • 1
    you want to check with null or zero? Commented Mar 26, 2015 at 5:18
  • I want to copy the comma separated values above ( 0,1,03:48:13,9) into an array (strs). I'm having trouble with CSVs that start with 0. CSV's that don't have 0s (which equal NULL in C) work fine. Commented Mar 26, 2015 at 5:22
  • Why would you compare with the literal digit "0" if you're checking for a null value? It's impossible for us to figure out what's wrong with your code because you've given us no idea what it's supposed to do. It seems you want to check for a NULL (no string at all), and then copy? If there's no string because the pointer is NULL, what's to copy? Commented Mar 26, 2015 at 5:29
  • Hint: what does == do? It tells you if two things are equal. What is pch? It's a pointer to a part of the line. What is "0"? It's a pointer to a constant string "0". What happens when you compare pointers with ==? Commented Mar 26, 2015 at 6:44
  • This question has nothing to do with NULL as far as I can tell. Commented Mar 26, 2015 at 6:44

1 Answer 1

2

You cannot able to check like this,

if(pch == "0"){
 ...
}

pch is pointer. You are comparing that with a string. So you have to make that as like this,

if ( *pch == '0' ) { 
 ...
}

Or else do like this,

if ( strcmp(pch,"0") == 0 ) {
 ...
}

It will help you to check the zero in a character string.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah I see... Thank you. Now when I'm adding that to the array of strings should I use the * notation for pch too?
if you are using strcpy then there is no need to give that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.