c - 我的代码中有一个问题,它没有使用带空格的完整字符串
问题描述
#include <stdio.h>
#include <stdlib.h>
struct fighter
{
char *name, *category;
int weight, age;
};
void enter_data(struct fighter *f, int n);
void display(struct fighter *f, int n);
int main(int argc, char const *argv[])
{
int n;
struct fighter *f;
printf("Enter no. of fighter: "); scanf("%d",&n);
f = (struct fighter *)malloc(n*sizeof(struct fighter));
enter_data(f, n);
display(f, n);
return 0;
for(int i=0; i<n; i++){
free((f+i)->name);
free((f+i)->category);
}
free(f);
}
void enter_data(struct fighter *f, int n){
for(int i=0; i<n; i++){
(f+i)->name=(char *)malloc(40*sizeof(char));
(f+i)->category=(char *)malloc(40*sizeof(char));
fflush(stdin);
printf("Enter name of fighter: ");
scanf("%s[^\n]",(f+i)->name);
//its not working full name, when I'm trying to give full name with space (ie. John Trump) its not working but when I'm giving only first name (ie. John) its working fine...
fflush(stdin);
printf("Enter age of fighter: ");
scanf("%d",&((f+i)->age));
printf("Enter weight of fighter: ");
scanf("%d",&(f+i)->weight);
printf("Enter category of fighter: ");
scanf("%s[^\n]",(f+i)->category);
}
}
void display(struct fighter *f, int n){
for(int i=0; i<n; i++){
printf("\n\n");
printf(" Name of fighter: ");
puts((f+i)->name);
printf(" Age of fighter: ");
printf("%d \n",(f+i)->age);
printf(" Weight of fighter: ");
printf("%d \n",(f+i)->weight);
printf(" Category of fighter: ");
puts((f+i)->category);
}
}
请参阅其中的enter_data()函数,我已经评论了我的问题...
当我用空格给出全名时,它不会占用其余的输入并直接跳转到循环的下一次迭代。但是当我给出名字或没有空格的名字时,它工作正常。
解决方案
此外,您return 0
应该在循环之后释放资源。
推荐阅读
- javascript - 清除过滤器功能不起作用Vue
- linux - 如何删除 Github 存储库
- angular - 提交后以角度重定向反应形式
- php - 错误:尝试使用 srmklive / laravel-paypal v.3 访问 null 类型值的数组偏移量
- flutter - Wheel ListView 小部件内的颤振按钮
- git - 如何在终端中重命名 git commit
- linux - 运行较新版本的 cURL 时的 SSL_ERROR_SYSCALL(错误 35)
- javascript - 将一个 div 居中并将右侧菜单附加到该 div
- xcode - 无效参数:Api 类型的对象/工厂已在 GetIt 中注册
- python - 从python字符串中删除引号