【问题标题】:There is a proble in my code, Its not taking full string with spaces我的代码有问题,它没有使用带空格的完整字符串
【发布时间】:2026-01-04 15:45:01
【问题描述】:
#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() 函数中查看我已经评论了我的问题...

当我用空格给出全名时,它不会占用其余部分 输入并直接跳到循环的下一次迭代。但是当我在 给出名字或没有空格的名字然后它工作正常。

This imgae is a output sceenshot when I'm giving full name.

This imgae is a output sceenshot when I'm giving first name only or name with no space.

【问题讨论】:

  • "%s[^\n]" 你可能想要"%[^\n]"
  • 我建议您考虑fgets()。不过,如果您要使用 scanf() ...并且如果您希望嵌入字符串...那么您的语法不正确。这是另一种选择:scanf("%[^\n]%*c", str):geeksforgeeks.org/…

标签: c scanf


【解决方案1】:

How do you allow spaces to be entered using scanf?

另外,您的return 0 应该在 循环之后释放资源。

【讨论】:

  • 你是对的......但你可能应该投票“关闭/重复”:(
  • 那我还能做吗?
  • 仍然无法正常工作...事实上,当我使用 scanf("%[^\n]%*c", (f+i)->name); 这不是请求输入的事件
  • 您阅读过发布的答案吗?最好不要使用scanf,使用(f+i)-&gt;name=(char *)malloc(40*sizeof(char)); fgets((f+i)-&gt;name, 40, stdin);
最近更新 更多