简体   繁体   English

从文本文件读取说明

[英]Reading instructions from a text file

I need help with reading instructions from a text file. 我需要阅读文本文件说明的帮助。 So for example: 因此,例如:

Let's say this is my text file: 假设这是我的文本文件:

a 38 一个38

s 20 s 20

a 10 10

s 10 10秒

'a' stands for add, 's' stands for subtract, and the number separated by a tab is the number I want to either add or subtract from a total. “ a”代表加法,“ s”代表减法,用制表符分隔的数字是我要加或减的总数。 So I want my program to read this line by line and perform the operation specified. 因此,我希望程序逐行读取此代码并执行指定的操作。

Example: If my total starts at 0, I want the program to read "a tab 38" on the first line and add 38 to the total, and then move on to the next line and read "s tab 20" on the second line and subtract 20 from the total. 示例:如果我的总数从0开始,我希望程序在第一行中读取“ a tab 38”并在总数中加38,然后移至下一行并在第二行中读取“ s tab 20”并从总数中减去20。 So on and so forth. 等等等等。

I know how to get the program to read the file, but I'm not sure how to get it to recognize the a/s, the tab, and the number, and then keep doing it for each line. 我知道如何获取程序来读取文件,但是我不确定如何获取它来识别a / s,制表符和数字,然后继续对每一行进行处理。

Any help would be greatly appreciated because I'm really stuck. 任何帮助将不胜感激,因为我真的很困。

Maybe you can try this . 也许您可以尝试一下。 Code I haven't checked properly but that should be the line of coding. 我没有正确检查代码,但这应该是代码行。 This is inside main function code. 这是主要功能代码内。

FILE *fp;
char buff[255];
char numBuff[10];

int a;
int val = 0;
char op;
int len;

fp = fopen("/tmp/test.txt", "r");


while(fgets(buff, 255, file) != NULL){
    len = strlen(buff);
    strncpy (numBuff, buff+2, len-2);
    numBuff[len-2] = '\0';

    a = atoi(numBuff);

    if(buff[0] == 's'){
        val -= a;
    }else if(buff[0]=='a'){
        val += a;
    }
}

printf("%d",val);

use fscanf(yourfileptr, "%c\\t%d", &instruction, &operand) to get the instruction and the operand. 使用fscanf(yourfileptr, "%c\\t%d", &instruction, &operand)获取指令和操作数。 then you can simply add or subtract the operand according to the instruction character. 那么您可以根据指令字符简单地增加或减少操作数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM