C Strtok使用和查找第二个元素

C Strtok使用和查找第二个元素,c,strtok,C,Strtok,我正在编写一个程序,要求用户输入两个单词,用逗号分隔。我还必须编写一个函数,查找字符串中的第二个单词,并将该单词复制到新的内存位置(不带逗号)。函数应返回指向新内存位置的指针。Main然后应该打印原始输入字符串和第二个单词 这是我目前的代码: #include <stdio.h> #include <string.h> #include <stdlib.h> char*secondWordFinder(char *userInput) int main (

我正在编写一个程序,要求用户输入两个单词,用逗号分隔。我还必须编写一个函数,查找字符串中的第二个单词,并将该单词复制到新的内存位置(不带逗号)。函数应返回指向新内存位置的指针。Main然后应该打印原始输入字符串和第二个单词

这是我目前的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char*secondWordFinder(char *userInput)

int main ()

{

        char*userInput;
        char*result;

        userInput=malloc(sizeof(char)*101);

        printf("Please Enter Two Words Separated by a comma\n");
        fgets(userInput,101, stdin);

        printf("%s",userInput);

        result=secondWordFinder(userInput);
        printf("%s",result);

        free(userInput);

        return 0;
}

    char*secondWordFinder(char *userInput)

    {
        char*userEntry;
        char*ptr;
        int i;
        i=0;

        for(i=0; i<strlen(userInput);i++)
        {
            userEntry=strtok(userInput, ",");
            userEntry=strtok(NULL,",");
            pointer=strcpy(ptr,userEntry);
        }
        return ptr;
    }
#包括
#包括
#包括
char*secondWordFinder(char*userInput)
int main()
{
字符*用户输入;
字符*结果;
userInput=malloc(sizeof(char)*101);
printf(“请输入两个用逗号分隔的单词\n”);
fgets(用户输入,101,标准输入);
printf(“%s”,用户输入);
结果=secondWordFinder(用户输入);
printf(“%s”,结果);
免费(用户输入);
返回0;
}
char*secondWordFinder(char*userInput)
{
char*userEntry;
char*ptr;
int i;
i=0;

对于(i=0;i提取第二个标记时,您说它后面必须跟一个逗号

userEntry = strtok(NULL, ",");
但它后面实际上是一个新行。试试这个:

userEntry = strtok(NULL, ",\n");
如果第二个单词是最后一个单词,但如果后面还有逗号分隔的单词,则此方法也有效

是的,你可以扔掉这个循环。

几个问题:

    for(i=0; i<strlen(userInput);i++)
    {
        userEntry=strtok(userInput, ",");
        userEntry=strtok(NULL,",");
        pointer=strcpy(ptr,userEntry);
    }
在返回第二个单词(如果存在)之前,您可能希望删除该单词后面的换行符;一种方法是

char *newline = strchr( userEntry, '\n' );
if ( newline )
  *newline = 0;
编辑

如果要求您必须将第二个字复制到
secondWordFinder
中的新缓冲区,并返回指向新缓冲区的指针,那么您必须按照

ptr = malloc( strlen( userEntry ) + 1 );
if ( ptr )
  strcpy( ptr, userEntry );

return ptr;

ptr
是未初始化的,因此尝试
strcpy
是一个错误(未定义的行为)。你没有得到什么?不清楚“在此处输入代码实际输出”是什么意思。你能澄清一下吗?你可以使用
sscanf()
提取第二个单词,它更紧凑、更可靠。并且停止使用malloc()用于函数范围存储。它只是
char userInput[101];
我当前的输出是:xxx,yyy,然后我得到xxx,yyy,但它不会打印出第二个标记,这是我必须打印出来的,以及原始输入字符串xxx,yyy,非常感谢!它现在可以工作了,但是我有一个问题,我必须将第二个标记复制到一个新的内存位置,以便我得去回忆一下?
ptr = malloc( strlen( userEntry ) + 1 );
if ( ptr )
  strcpy( ptr, userEntry );

return ptr;