首页 > 解决方案 > 确定文本文件 C 中的数字或字符

问题描述

我有一个文本文件,其中包含以下数字和字符。

36@xL!?\8
28?>\4
42<pX%7
37@#5
31kL%^?>\<#%5

现在,我想得到第一个整数 36,然后在最后一个整数 8 上减去它。我想逐行执行此操作。

标签: cgcctext-filesfile-handling

解决方案


您想在该行中读取,解析开头和结尾的数字,然后将它们转换为整数。这是一个简单的例子:

#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);
}

推荐阅读