简体   繁体   中英

fscanf not reading char from file

I have a program that reads from a file and converts assembly code into VM machine code. Instructions have different datatypes depending on the opcode, so my reader looks like this:

while(!feof(inF)) {
    fscanf(inF, "%s",&temp); //analyse first string and branch into if statement 
        printf("%s\n", temp);
        if (strcmp(temp, "NOP") == 0 || strcmp(temp, "nop") == 0) {
            fprintf(outF, "%i\n", 0);
        }
        else if (strcmp(temp, "LDI") == 0 || strcmp(temp, "ldi") == 0) {
            opcode = LDI; //opcode 1
            fscanf(inF," %c %d", &r1, &immediate); //get r1 and immediate
            printf("R1: %i\n", r1);
            printf("I: %i\n", immediate);
            r1 = getReg(r1);
            r2 = 0;
            subop = 0;
            output = (opcode << 27)|(r1 << 24)|(r2 << 21)|(subop << 16)|(immediate);
            fprintf(outF, "%x\n", output);
        }        
}

With a line reading LDI A 1024 , I get an output of :

LDI
R1: 0
I: 1024

Instead of the expected

LDI
R1: 65
I: 1024

It appears that fscanf is not reading the char . I've looked at solutions that seemed to work for others and they don't seem to work here for some reason.

You have declared the variable immediate as unsigned short while the line

fscanf(inF," %c %d", &r1, &immediate);

supposes it is an integer. The behavior is undefined in such cases.

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