【发布时间】: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