strtok的未正常工作 [英] strtok not working as expected

查看:81
本文介绍了strtok的未正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写,获取一个指向字符数组的函数,读取来自用户的字符串,删除字符串直到第一个字符不是串出现的开始所有空间。最后,在开始时返回字符串的副本,而不空间/秒。

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.

例如,

输入 ABCD 函数应该返回字符串指针 ABCD

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

输入 123 123 函数应该返回指向字符串 123 123

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

功能如下所示,

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.**/
}

但因故功能的strtok()并不如预期的工作。

在输入时:

   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

有什么建议?

推荐答案

strtok的工作完全按照预期。它打破了输入分割成字符串 123 456

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);

这篇关于strtok的未正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆