我正在学习C中的文本文件主题,我有一个问题:我可以用什么来代替__fpurge(stdin);,而又能让这个函数像__fpurge(stdin);一样工作,而且我不允许在这个程序中包含<stdlib.h>。我已经读过这篇c - need an alternative for fflush了,但是只要我不被允许使用#include <stdlib.h>,我就不能使用strtol。
void generateBill() {
FILE *fp, *fp1;
struct Bill t;
int id, found = 0, ch1, brel = 0;
char billname[40];
fp = fopen(fbill, "rb");
printf("ID\tName\tPrice\n\n");
while (1) {
fread(&t, sizeof(t), 1, fp);
if (feof(fp)) {
break;
}
printf("%d\t", t.pid);
printf("%s\t", t.pname);
printf("%d\t\t\t\n", t.pprice);
total = total + t.pprice;
}
printf("\n\n=================== Total Bill Amount %d\n\n", total);
fclose(fp);
if (total != 0) {
//__fpurge(stdin);
printf("\n\n\n Do you want to generate Final Bill[1 yes/any number to no]:");
scanf("%d", &ch1);
if (ch1 == 1) {
brel = billFileNo();
sprintf(billname, "%s%d", " ", brel);
strcat(billname, "dat");
fp = fopen(fbill, "rb");
fp1 = fopen(billname, "wb");
while (1) {
fread(&t, sizeof(t), 1, fp);
if (feof(fp)) {
break;
}
fwrite(&t, sizeof(t), 1, fp1);
}
fclose(fp);
fclose(fp1);
fp = fopen(fbill, "wb");
fclose(fp);
}
total = 0;
}
}发布于 2021-05-02 12:56:16
对于__fpurge(stdin)的替代方案,建议:
int ch;
while( (ch = getchar() ) != EOF && ch != '\n' ){;}它只需要#include <stdio.h>
发布于 2021-05-04 00:51:27
__fpurge是一个仅在某些系统上可用的非标准功能(glibc 2.1.95,IBM zOS...)这将丢弃读取到流缓冲区中尚未被getc()使用的输入。
正如linux manual page中所解释的,通常情况下,想要丢弃输入缓冲区是错误的。
您可以使用scanf()读取用户输入,它会在请求的转换完成时停止扫描输入,例如,当%d读取不能继续数字的字符时,它会停止读取用户键入的字符,并将此字符留在输入流中。因为stdin在连接到终端时通常是行缓冲的,所以在处理输入之后,您应该只读取并丢弃用户输入的行中的任何剩余字节。
下面是一个用于此目的的简单函数:
int flush_input(FILE *fp) {
int c;
while ((c = getc(fp)) != EOF && c != '\n')
continue;
return c;
}您将在处理用户输入之后调用此函数,并且应该测试scanf()的返回值,以确保用户输入具有预期的语法。
以下是您的函数的修改版本:
#include <errno.h>
#include <string.h>
// return a non zero error code in case of failure
int generateBill(void) {
FILE *fp, *fp1;
struct Bill t;
int id, found = 0, ch1, brel = 0;
char billname[40];
fp = fopen(fbill, "rb");
if (fp == NULL) {
fprintf(sdterr, "cannot open %s: %s\n", fbill, strerror(errno));
return 1;
}
printf("ID\tName\tPrice\n\n");
while (fread(&t, sizeof(t), 1, fp) == 1) {
printf("%d\t", t.pid);
printf("%s\t", t.pname);
printf("%d\t\t\t\n", t.pprice);
total = total + t.pprice;
}
printf("\n\n=================== Total Bill Amount %d\n\n", total);
if (total != 0) {
int res;
printf("\n\n\n Do you want to generate Final Bill[1 yes/any number to no]:");
while ((res = scanf("%d", &ch1)) == 0) {
fprintf("Invalid input. Try again\n");
flush_input(stdin);
}
flush_input(stdin);
if (res == EOF) {
fprintf("premature end of file on input\n");
fclose(fp);
return 2;
}
if (ch1 == 1) {
brel = billFileNo();
snprintf(billname, sizeof billname, "bill-%d-dat", brel);
rewind(fp);
fp1 = fopen(billname, "wb");
if (fp1 == NULL) {
fprintf(sdterr, "cannot open %s: %s\n", billname, strerror(errno));
fclose(fp);
return 1;
}
while (fread(&t, sizeof(t), 1, fp) == 1) {
fwrite(&t, sizeof(t), 1, fp1);
}
fclose(fp1);
}
}
fclose(fp);
return 0;
}https://stackoverflow.com/questions/67346539
复制相似问题