Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c - strtok not working as expected

I tried to write a function that gets a pointer to array of char, reads a string from the user and remove all spaces in the start of the string till the first char that is not string appear. Finally return the copy of the string without space/s in the begining.

For example,

for input abcd the function should return pointer to the string abcd.

for input 123 123 the function should return pointer to string 123 123.

The function is shown below,

void read_RemoveSpace(char * str)/**read the rest of string**/
{
    char tempRead[30];
    fgets(tempRead,30,stdin);
    char *ptr = strtok(tempRead, " "); /**remove spaces between command and other data**/
    strcpy(str,ptr); /**copy the new string without the spaces.**/
}

But some reason the function strtok() is not working as expected.

In case of input:

   123 456

the function returns only the first part without the spaces but not the rest of the string, i.e. it points to

123

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

strtok is working exactly as expected. It breaks the input apart into the strings 123 and 456.

strtok (tempRead, " "); /* Returns 123 */
strtok (NULL, " "); /* Returns 456 */

I think you can do with a simpler solution:

int i = 0;
char tempRead[30];
...
while (tempRead[i] == ' ' && tempRead[i])
  i++;
strcpy(str,tempRead+i);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...