c - 从文本中获取特定字符并在 C 中打印相关行
问题描述
我在 C 中的 I/O 文件处理有几个问题。我有一个这样的文本文件:
AAA 1 80
BBB 1 60
CCC 2 20
DDD 1 70
EEE 2 15
FFF 2 30
GGG 2 75
HHH 1 25
JJJ 2 35
我的目标是如果用户输入 1 我需要打印:
AAA 1 80
BBB 1 60
DDD 1 70
HHH 1 25
并总结它们的值(80+60+70+25),如果用户输入 2,则应用相同的东西。
我编写了这样的代码:
FILE *fPtr;
char str[MAXCHAR];
char* fileName = "/home/levent/Masaüstü/data.txt";
int productType;
fPtr = fopen(fileName, "r");
if(fPtr == NULL){
printf("Error! Colud not find file %s", fileName);
return 1;
}
printf("Enter product type code (1 or 2): ");
scanf("%d", &productType);
while (fgets(str, MAXCHAR, fPtr) != NULL){
printf("%s", str);
}
正如您假设此代码打印整个文本文件一样。如何管理我的目标?
解决方案
您可以使用fscanf
和解析每一行的每个组件,然后在同一个循环中,您可以对有效值求和:
以下是一些评论的可能实施:
//...
#define MAXCHAR 100
//...
int fileProductType; //product type read from file
int value; //value read from file
int sum = 0; //to store the sum of the values
//...
//scan all file lines
while (fscanf(fPtr, "%99s %d %d", str, &fileProductType, &value) == 3){
if (productType == fileProductType){ //if the type is correct
printf("%s %d %d\n", str, fileProductType, value); //print line
sum += value; //sum values
}
}
if(sum) //if the product type is found
printf("Sum: %d\n", sum); //print sum
else
puts("No mach found!");
//...
另一种选择是用于sscanf
解析fgets
. 其余的将或多或少相同。
推荐阅读
- html - 将图像粘贴到 div 的底部 - 响应式图像问题(网格/填充)
- discord.js - 让 Rock、Paper、Scissors 在 discord.js 中通过反应工作
- c# - 将多个文本框中的值插入一列,但为每个文本框值创建一个新行
- video-streaming - raspberrypi 中的 AWS kinesis 视频流。无法创建 Kinesis 视频流
- python - 如何在 Django 中列出从答案模型到我的问题模型的所有答案?多对一的关系?
- javascript - 填写字段+活动复选框时,我们激活按钮
- firebase - Firestore RESTful API 查询仅返回 readTime 作为有效负载
- javascript - Rails 远程和 jquery ajaxStop
- javascript - 将数组的内容作为列表元素添加到无序列表
- javascript - 在 Javascript 中选择数组时遇到问题