#include <stdio.h>
#include <ctype.h> /* for access to the toupper function */
void reverse_name(char *name);
int main(void)
{
char input[100];
printf("Enter a first and last name: ");
gets(input);
reverse_name(input);
return 0;
}
void reverse_name(char *name){
char *first = name;
char *see;
see = name;
while(*see != ' '){
}
while(*see != '\n'){
putchar(*see);
}
printf(", %c",*first);
}
我希望发生这种情况:输入名字和姓氏:Lloyd Fosdick
输出如下:Fosdick, L.
但是在输入名字和姓氏 Lloyd Fosdick 后,程序没有给出任何答案,也没有任何反应?代码有什么问题吗?
最佳答案
您既不增加 see
也不在两个 while 循环中检查 0
终止符:
while(*see && *see != ' '){
see++;
}
while(*see && *see != '\n'){
putchar(*see);
see++;
}
gets()
已从 C11 中删除,即使您遵循旧标准,也不应该使用它。请改用 fgets()
。
这绝不是一个完整的修复。你必须问自己:
- 如果输入的名称之间包含多个空格怎么办?
- 如果输入包含两个以上的姓名怎么办?
- 如果没有名字或姓氏怎么办?
- 等等。
您需要考虑所有这些情况并在代码中处理它们。
关于c - 字交换期间无输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32028283/