gpt4 book ai didi

c - 在 C 中扫描文本文件中的值时如何清除输入缓冲区?

转载 作者:行者123 更新时间:2023-11-30 20:43:31 25 4
gpt4 key购买 nike

#include <stdio.h>
#define MAX_TITLE_SIZE 20
#define MAX_BOOKS 10

struct Book {
int _isbn;
float _price;
int _year;
char _title[MAX_TITLE_SIZE + 1];
int _qty;
};

void clear(void);
int readRecord(FILE *fp, struct Book *b2read);
void displayInventory(const char filename[]);



int main(void) {

struct Book myBook;
char filename[21] = "144_w9_inventory.txt";

displayInventory(filename);

return 0;
}

void clear(void) {

while (getchar() != '\n');

}

int readRecord(FILE *fp, struct Book *b2read){

//Define a variable int rv = 0
int rv = 0;


rv = fscanf(fp, "%d;%f;%d;%d;%20[^\n]", &(b2read->_isbn), &(b2read->_price), &(b2read->_year), &(b2read->_qty), b2read->_title);
//return rv;

return rv;
}

void displayInventory(const char filename[]) {

struct Book myBook;

FILE *fp = NULL;
int i;

fp = fopen(filename, "r"); //open the file for reading

if (fp != NULL) {

printf("\n\nInventory\n");
printf("===================================================\n");
printf("ISBN Title Year Price Quantity\n");
printf("---------+-------------------+----+-------+--------\n");

while(readRecord(fp, &myBook) == 5){
printf("%-10.0d%-20s%-5d$%-8.2f%-8d\n", myBook._isbn, myBook._title, myBook._year, myBook._price, myBook._qty);
}
printf("===================================================\n");
printf("\n");

fclose(fp);
}
else {
printf("Failed to open file\n");
}
}

文本文件中的内容是:

234562;23.99;2010;3;Harry Potter
567890;12.67;2015;4;The Hunger Games
109821;53.20;2017;2;Stranger Things

输出:

Inventory
===================================================
ISBN Title Year Price Quantity
---------+-------------------+----+-------+--------
234562 Harry Potter
2010 $23.99 3
567890 The Hunger Games
2015 $12.67 4
109821 Stranger Things 2017 $53.20 2
===================================================

当我输出程序时,我能够获取所有值,但由于某种原因,当我打印这些值时,整个字符串被减半并向下移动一行。

如果您想看一下,repl.it 就在这里:

https://repl.it/JbRy/69

如何获得以单行打印的输出;如果是这样的话,而不是读取\n“换行符”?

最佳答案

它与“清除输入缓冲区”无关。 fscanf() 根据您指定的内容使用它。它不需要“清除”,它需要正确扫描。不知何故,你在标题中得到了行终止符。更正您的 fscanf() 格式字符串。

关于c - 在 C 中扫描文本文件中的值时如何清除输入缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45227524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com