【问题标题】:Strtok use and finding the second elementStrtok 使用和查找第二个元素
【发布时间】:2014-03-04 21:28:25
【问题描述】:

我正在编写一个程序,要求用户输入两个单词,用逗号分隔。我还必须编写一个函数来查找字符串中的第二个单词并将该单词复制到一个新的内存位置(不带逗号)。该函数应该返回一个指向新内存位置的指针。然后 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;
    }

我在这里没有得到 a`enter 代码实际输出我做错了什么???

【问题讨论】:

  • ptr 未初始化,因此尝试strcpy 是一个错误(未定义的行为)。
  • 你没有得到什么?目前尚不清楚“a`enter code here实际输出”是什么意思。你能澄清一下吗?
  • 第二个单词可以使用sscanf()提取,更加简洁可靠。
  • 并停止使用 malloc() 进行函数范围存储。这只是char userInput[101];
  • 我当前的输出是:xxx,yyy 然后我得到 xxx,yyy 但它不会打印出第二个标记,这是我必须与原始输入字符串一起打印出来的是 xxx,yyy

标签: c strtok


【解决方案1】:

在提取第二个token时,你说后面必须跟一个逗号。

userEntry = strtok(NULL, ",");

但实际上后面是换行符。试试这个:

userEntry = strtok(NULL, ",\n");

如果第 2 个单词是最后一个单词,则此方法有效,但如果后面有更多逗号分隔的单词。

是的,你可以扔掉循环。

【讨论】:

    【解决方案2】:

    几个问题:

        for(i=0; i<strlen(userInput);i++)
        {
            userEntry=strtok(userInput, ",");
            userEntry=strtok(NULL,",");
            pointer=strcpy(ptr,userEntry);
        }
    
    • 您正在为输入字符串中的每个字符重复这些操作,这没有任何意义 - 这根本不需要循环;
    • 您尚未初始化 ptr 以指向任何有意义的位置,因此您正尝试将 userEntry 复制到某个随机内存块;
    • 在第二次调用strtok 之后,userEntry 已经指向第二个字符串 - 您可以简单地返回 userEntry

    你应该可以把它改写为

    strtok(userInput, ", "); // accounts for any spaces between the comma and next string
    userEntry = strtok( NULL, ", ");
    return userEntry;
    

    您可能希望在返回第二个单词(如果存在)之前删除尾随的换行符;一种方法是

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

    编辑

    如果要求您必须将第二个单词复制到secondWordFinder 中的新缓冲区并返回指向新缓冲区的指针,那么您将不得不按照以下方式做一些事情

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

    【讨论】:

    • 非常感谢!它现在可以工作了,但是我有一个问题,我必须将第二个令牌复制到一个新的内存位置,所以我必须 malloc 内存吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 2019-03-24
    • 2019-11-06
    • 1970-01-01
    • 2019-08-28
    • 2016-02-29
    相关资源
    最近更新 更多