简体   繁体   中英

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

s 20

a 10

s 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. 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. 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.

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. then you can simply add or subtract the operand according to the instruction character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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