c - 确定文本文件 C 中的数字或字符
问题描述
我有一个文本文件,其中包含以下数字和字符。
36@xL!?\8
28?>\4
42<pX%7
37@#5
31kL%^?>\<#%5
现在,我想得到第一个整数 36,然后在最后一个整数 8 上减去它。我想逐行执行此操作。
解决方案
您想在该行中读取,解析开头和结尾的数字,然后将它们转换为整数。这是一个简单的例子:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
main()
{
FILE *file = fopen("input.txt", "r");
char line[256];
while (fgets(line, sizeof(line), file))
{
char num[15];
int firstNumber = 0;
int secondNumber = 0;
line[strcspn(line, "\r\n")] = 0;
for (int x = 0; x < 256; x++)
{
if (isdigit(line[x]))
{
num[x] = line[x];
}
else
{
num[x] = 0;
break;
}
}
firstNumber = atoi(num);
int length = strlen(line);
int ndx = 0;
while (length >=0 && isdigit(line[length - 1]))
{
num[ndx] = line[length - 1];
ndx++;
length--;
}
num[ndx] = 0;
secondNumber = atoi(num);
printf("%d - %d = %d\n", firstNumber, secondNumber, firstNumber - secondNumber);
}
fclose(file);
}
推荐阅读
- java - selenium 测试执行期间的高 CPU 负载
- dhall - 是否可以从 _within_ 一个 dhall 表达式创建 YAML?
- java - 如何使从 COLOR 类获得的 HSB 颜色变为半透明(半透明)?
- android - Sentry:使用 Gradle 组装时未上传 Proguard 映射
- apache-kafka - 计算 Kafka 主题中的消息
- java - 无法从 Booking.com 的搜索结果中获取价格
- internet-explorer - centos 7无法安装IE
- node.js - 尝试使用 Google 官方库从 Node.js 接收 Gmail 时出错
- c - 如何声明可变长度数组并将其初始化为零?
- ios - SwiftUI Text 似乎依赖于 Image