简体   繁体   中英

strtok() reading the spaces at the end of string and not returning NULL

I am using fgets() to read a line which contains integers values separated by spaces as follows:

while(fgets(str, sizeof(str), stdin) != NULL)

After reading string in str, I am using strtok() to convert string in to tokens and then using atoi() function to convert these values in to integers.

token = strtok(str, s);
while( token != NULL)    //If token is NULL then don't convert it to integer
int d = atoi(token);

The output of the first input is as expected.

Input-1:

5 1 0 3 4\n

Output-1:

d=5
d=1
d=0
d=3
d=4

Now the problem occurs when I give a space after string and hit enter.

Input-2:

5 1 0 3 4 \n

Output-2:

d=5
d=1
d=0
d=3
d=4
d=0

So now my questions are:

1. Will strtok() not return NULL when there are only spaces at the end?

2. How to differentiate between the two zeros that are coming in output?

3. How can I avoid strtok() to read that final space or any number of spaces at the end?

Your problem is with the delimiter(s). One solution for all your questions is :

Please add space [ ] and newline [ \\n ] both to your delimiter string, and optionally \\t .

As per the man page of strtok()

char *strtok(char *str, const char *delim);

The delim argument specifies a set of bytes that delimit the tokens in the parsed string.

and

A sequence of two or more contiguous delimiter bytes in the parsed string is considered to be a single delimiter.

So, you can use

char *s = " \n\t"

and then

token = strtok(str, s);

The function you are using is not correct.Delimiter passed as a 2nd parameter should be correct.

token = strtok(str," \n\t");  //should use delimiter
while( token != NULL) 
{
   int d = atoi(token);
   printf("%d\n",d);
   token = strtok(NULL," \n\t");
}

Signature of the strtok is char *strtok(char *str, const char *delim);

delimiter can be space [ ], newline \\n , coma [,] , tab [\\t] anything that separate the two values in your string in a constant significant fashion are considered as delimiter. Delimiter characters at the start or end of the string are ignored by strtok.

You can use n no of delimiter. as per your string you can use two delimiter 1. space [ ] 2. \\n

change:

1.token = strtok(str, " \\n"); 2.token = strtok(NULL," \\n");

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