Thursday, July 30, 2009

C programming question?

Hey


Can't I print the tokens using strtok with "%s"


in the printf argument? e.g.("%s", token);





Every time I try to print a token with "%s", it gives me weird


output, like one character missing at the front, or not printing


at all.





By the way, does Token have the same format as a string?


Because I have been trying to compare token with string, and they never ever equal to each other, do I need casting or something?





I have been stuck in this for many, many hours now in my


assignment. I would like some help. Thank you very much.





My following statement in the assignment never equals to each other.


if(strcmp(line2, token) == 0)

C programming question?
Hmmm... sounds like you shouldn't be having a problem. Are you calling the sequential calls to strtok() with NULL?





#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;





int main(void) {


char myStr[] = "Here is a sample string."


char *tokPtr;





tokPtr = strtok (str," .");


while (tokPtr != NULL) {


printf ("%s\n",tokPtr);


tokPtr = strtok (NULL, " .");


}





return 0;


}





Also don't forget that the delimeters are replaced with a '\0' and therefor will not be in the returned tokens. In memory, the string at the point of the "return 0;" would look like:





[H] [e] [r] [e] [\0] [i] [s] [\0] [a] [\0] [s] [a] [m] [p] [l] [e] [\0] [s] [t] [r] [i] [n] [g] [\0]

petal

No comments:

Post a Comment