确定文本文件C中的数字或字符 [英] Determine number or character in textfile C

查看:55
本文介绍了确定文本文件C中的数字或字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a textfile with these following numbers and characters inside of it.

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

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

Now, i want to get the first integer which is 36 and subtract it on the last integer which is 8. I want to do this line by line.

推荐答案

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

You want to read in the line, parse the numbers at the beginning and end, then convert them to integers. Here is a simple example:

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

这篇关于确定文本文件C中的数字或字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆