【问题标题】:Array of structs doesn't take input properly [duplicate]结构数组没有正确接受输入[重复]
【发布时间】:2019-07-30 18:04:41
【问题描述】:

每次我尝试使用结构数组并从用户那里获取输入时,它都会跳过 scanf,我不知道为什么。 我通过创建仅包含 1 个元素的数组并仅扫描该元素而不是使用 for 循环来简化代码,但它仍然不起作用。

#include <stdio.h>
#include <string.h>

int main(){

  typedef struct {
    char title[30];
    char author[30];
    int year;
  } Books;

  Books library[1]; //array of structs

  //input
    printf("\nAdd a new book to the shelf");
    printf("\nTitle: ");
    scanf("%[^\n]",library[0].title);
    printf("\nAuthor: ");
    scanf("%[^\n]",library[0].author);
    printf("\nYear: ");
    scanf("%d",&library[0].year);

  //print
    printf("\nTitle: ");
    printf("%s",library[0].title);
    printf("\nAuthor: ");
    printf("%s",library[0].author);
    printf("\nYear: ");
    printf("%d\n",library[0].year);

    return 0;
}

终端:

Add a new book to the shelf
Title: Fist Book  //input by user

Author:                 //doesn't let me scan anything and jumps to Year: 
Year: 1998 //input

Title: Fist Book 
Author: 
Year: 1998

【问题讨论】:

  • "%[^\n]" 不会跳过空格。试试" %[^\n]"
  • 这不是结构数组。那是一个 single 结构。您可能希望将您的图书结构命名为 Book 而不是 Books,因为它只是一个,而不是多个。
  • @user3386109 非常感谢!这确实有效,但我不知道为什么。你能解释一下区别吗?
  • 问题顶部黄色框中的链接导致问题重复。该问题的答案解释了空间的作用,并为问题提供了替代解决方案。

标签: c arrays struct


【解决方案1】:

scanf 中,%[^\n] 不会跳过空格。要跳过空格(应该可以解决您的问题),请执行以下操作:

scanf(" %[^\n]", library[num].member);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多