这篇文章附带的代码是一个更大程序的一部分,但我在接受结构化变量“标题”和“作者”的输入时遇到了问题。 该程序似乎循环遍历它并转到下一行。另外,在字符串说明符中的 's' 之前使用 [^\n] 时,它的作用相同,但我读到它用于使用 scanf 将字符串作为输入。看了几篇帖子,还是没明白问题所在。 刚从 C 开始,任何帮助将不胜感激!
struct books{
char title[30];
char author[30];
char subject[20];
int quantity;
int book_id;
char *category;
int count;
float price;
};
struct books book;
book.book_id=id;
printf("\n\n\t\tBook Name:\n\t\t");
scanf(" %s",book.title);
printf("\n\n\t\tAuthor:\n\t\t");
scanf(" %[^\n]s",book.author);
printf("\n\n\t\tQuantity:\n\t\t");
scanf("%d",&book.quantity);
printf("\n\n\t\tPrice:\n\t\t");
scanf("%f",&book.price);
最佳答案
在输入“book.title”和“book.author”中,在字符串说明符的“s”之前使用 [^\n]。
我执行了您的代码并进行了这些修改。代码正确。
您一直使用空格分隔的字符串作为书名。(例如“Mein Kampf”作为书名。)
但是您必须了解您无法使用 Scanf 将空格分隔的单词作为单个字符串输入。因此程序会对其进行循环并移至下一行。
要获取此类输入,您必须使用 gets 或 fgets 函数,或者在字符串说明符中的 's' 之前使用 [^\n]。
关于c - 使用 scanf 进行结构输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42871771/