gpt4 book ai didi

似乎无法将输入与文本文件中的值匹配

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

这是 items.txt 包含的内容:

275,Fresh Fish,12.34,0
386,Soft kleenex,45.67,1
240,Ultra Tide,24.34,1
916,Red Apples,123.45,0
385,Magic Broom,456.78,1
495,Liquid Soap,546.02,1
316,Chocolate Cookies,78.34,1
355,Organic Milk,24.34,0
846,Dark Chocolate,123.45,1
359,Organic Banana,99.99,0

当用户输入“Y”时如何倒回文件?如果我第一次输入正确的值,它就会起作用。

#include <stdio.h>
#define TAX (0.13)
void keybFlush(){
while(getchar() != '\n');
}
int getInt(){
int val;
char nl = 'x';
while (nl != '\n'){
scanf("%d%c", &val, &nl);
if (nl != '\n'){
keybFlush();
printf("Invalid Integer, please try again: ");
}
}
return val;
}
int yes(){
char ch = 'x';
int res;
do{
ch = getchar();
res = (ch == 'Y' || ch == 'y');
keybFlush();
} while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N' && printf("Only (Y)es or (N)o are acceptable: "));
return res;
}
int main(){
int upc, userUpc, found = 0;
double price;
int isTaxed, i;
char item[21], ch, x, y;
FILE* fptr = fopen("items.txt", "r");
if (fptr){
do {
userUpc=getInt();
printf(" UPC | Name | Price | Tax | Total\n"
" -----+--------------------+-----------+---------+-----------\n");
printf("its : %d\n", userUpc);
while (!feof(fptr)){
fscanf(fptr, "%d,%[^,],%lf,%d", &upc, item, &price, &isTaxed);
if ( upc == userUpc){
if(!feof(fptr)){
printf("%-6d|%-20s|%11.2lf|", upc, item, price);
if (isTaxed)
printf("%9.2lf|%11.2lf\n", price * TAX, price * (1+TAX));
else
printf("%9.2lf|%11.2lf\n", 0.0, price);
found = 1;
}
}
}
if (!found){
printf("Can't find any matched records\n");
}
printf("Do you want to continue: ");
i=yes(); // if yes, rewind the file
} while (!userUpc || (i == 1));
fclose(fptr);

}
else{
printf("could not open the file\n");
}
return 0;
}

如果我输入“y”继续并输入正确的值,它似乎无法正确输出。

最佳答案

要将文件光标的位置更改为文件开头:

fseek(filePtr, 0, SEEK_SET);

有关文件操作的更多信息: http://www.gnu.org/software/libc/manual/html_node/File-Positioning.html

关于似乎无法将输入与文本文件中的值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27065757/

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