我创建了以下两个函数。第一个,eatWrd,返回一个没有任何空格的字符串中的第一个单词,并从输入字符串中删除第一个单词:
MAX是表示字符串
的最大长度的数字char* eatWrd(char * cmd)
{
int i = 0; //i will hold my place in cmd
int count = 0; //count will hold the position of the second word
int fw = 0; //fw will hold the position of the first word
char rest[MAX]; // rest will hold cmd without the first word
char word[MAX]; // word will hold the first word
// start by removing initial white spaces
while(cmd[i] == ' ' || cmd[i] == '\t'){
i++;
count++;
fw++;
}
// now start reading the first word until white spaces or terminating characters
while(cmd[i] != ' ' && cmd[i] != '\t' && cmd[i] != '\n' && cmd[i] != '\0'){
word[i-fw] = cmd[i];
i++;
count++;
}
word[i-fw] = '\0';
// now continue past white spaces after the first word
while(cmd[i] == ' ' || cmd[i] == '\t'){
i++;
count++;
}
// finally save the rest of cmd
while(cmd[i] != '\n' && cmd[i] != '\0'){
rest[i-count] = cmd[i];
i++;
}
rest[i-count] = '\0';
// reset cmd, and copy rest back into it
memset(cmd, 0, MAX);
strcpy(cmd, rest);
// return word as a char *
char *ret = word;
return ret;
}
第二个,frstWrd,只返回第一个单词而不修改输入字符串:
// this function is very similar to the first without modifying cmd
char* frstWrd(char * cmd)
{
int i = 0;
int fw = 0;
char word[MAX];
while(cmd[i] == ' ' || cmd[i] == '\t'){
i++;
fw++;
}
while(cmd[i] != ' ' && cmd[i] != '\t' && cmd[i] != '\n' && cmd[i] != '\0'){
word[i-fw] = cmd[i];
i++;
}
word[i-fw] = '\0';
char *ret = word;
return ret;
}
为了测试这个函数,我用fgets从User(me)中读取一个字符串,然后我打印了三个字符串(frstWrd(输入),eatWrd(输入),eatWrd(输入))。我原本以为给了一个字符串,"我的名字是蒂姆"例如,程序将打印"我的名字",而是它打印第三个单词三次," is is is":
// now simply test the functions
main()
{
char input[MAX];
fgets(input, MAX - 1, stdin);
printf("%s %s %s", frstWrd(input), eatWrd(input), eatWrd(input));
}
我一遍又一遍地查看我的功能,看不出错误。我相信有些东西我不了解printf,或者在另一个函数中使用多个字符串修改函数作为参数。任何见解都会有所帮助,谢谢。
答案 0 :(得分:1)
我看到rest
和word
是函数eatWrd
中的局部变量。因此,在函数外部返回指向此类内存的指针是不好的做法。
编辑1:
另外你应该明白,在行
printf("%s %s %s", frstWrd(input), eatWrd(input), eatWrd(input));
函数eatWrd(input)
可以被称为第一个(frstWrd(input)
之前)。
编辑2:
这在结尾eatWrd
//char rest[MAX]; // rest will hold cmd without the first word
char * rest = (char*) malloc(MAX);

新主要是:
int main()
{
char input[MAX];
fgets(input, MAX - 1, stdin);
printf("%s ", frstWrd(input));
printf("%s ", eatWrd(input));
printf("%s\n", eatWrd(input));
}

最后我的frstWrd
解决方案(仅用于展示标准函数如何有用):
char* frstWrd(char * cmd)
{
char * word = (char *) malloc(MAX);
sscanf(cmd, "%s", word);
return word;
}