【发布时间】:2026-01-04 19:10:01
【问题描述】:
我创建了以下两个函数。第一个,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(input)、eatWrd(input)、eatWrd(input))。我本来希望给定一个字符串,例如“my name is tim”,程序会打印“my my name”,但它会打印第三个单词三次,“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,或者关于在另一个函数中使用多个字符串修改函数作为参数,我完全不知道一些事情。任何见解都会有所帮助,谢谢。
【问题讨论】:
-
只有一长段描述您的问题很难阅读。尝试以某种方式拆分信息。
-
相关:您应该想知道在您的
printf()参数中是否对这三个函数调用的执行顺序有任何保证。 (剧透:没有这样的保证)。您的返回值中显然存在 未定义的行为(请参阅下面的 Volands 回答)。 -
ty,我个人认为现在好多了。
-
重复,*.com/questions/25798977/…(以及其他十几个线程)
标签: c string function printf word