Question

int stringCheck(char*);

void compile(int *instructionSet2, int *accumulator2, int *instructionCounter2, int *instructionRegister2, int *operationCode2, int *operand2)
{

    char *readIn;
    readIn = (char*)malloc(sizeof(char)*11);

    while(fgets(readIn,11,stdin) != NULL)
    {
        *instructionCounter2 = scanf("%d",(int*)readIn);
        instructionSet2[*instructionCounter2] = (stringCheck((char*)scanf("%s",readIn)));
        instructionSet2[*instructionCounter2] += (scanf("%d",(int*)readIn));
    }
}

int stringCheck(char *stIn)
{
    if (strcmp(stIn,"READ") == 0)
    {
        return 10 * 100;
    } /* Snipped to just give an idea of the numeric value assignment for words read. */
}

Alright, what I'm trying to do here is figure out how to properly read in a set of instructions like this:

00 READ 9
01 READ 10
02 LOAD 9
03 SUB 10
04 BRNG 7
05 WRIT 9
06 HALT 99
07 WRIT 10
08 HALT 99
09 SET 0
10 SET 0

I've gotten myself a little stuck though on trying to read in the words. Basically, I just want to scan in an int, a string, and then another int and continue doing this while the end of file isn't reached.

It turns out that scanf returns the number of characters successfully read instead of pointers so the second line inside the while loop is warning me of that when compiling.

I'm trying to fix this warning in particular:

virtualcomp.c:66:56: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

Points to this line specifically:

instructionSet2[*instructionCounter2] = (stringCheck((char*)scanf("%s",readIn)));

How can I fix this?

NOTE: I'm trying to avoid putting in more variables, only using the ones present.

Was it helpful?

Solution

You can parse all three variables with one scanf call. Note scanf returns the number of input variables assigned. I think you need something like this:

int n1, n2;
char buf[12];
...
...
sscanf(readIn, "%d %s %d",&n1, buff, &n2);

*instructionCounter2 = n1;
instructionSet2[*instructionCounter2] = stringCheck(buff);
instructionSet2[*instructionCounter2] += n2;

OTHER TIPS

Trying to to an int into a generic buffer (of size 11) is unorthodox.

char *readIn;
readIn = (char*)malloc(sizeof(char)*11);
...
*instructionCounter2 = scanf("%d",(int*)readIn);

Suggest instead dropping the malloc() and reading directly into the 2 int.

char s[11];
char readIn[21 + sizeof s + 21 + 2];  // 21 is chars in a 64-bit int
while(fgets(readIn, sizeof readIn, stdin) != NULL)
{
   int n;
   if (sscanf(readIn, "%d%n", instructionCounter2, &n) != 1 || 
       sscanf(&readIn[n], "%11s%d",s,&instructionSet2[*instructionCounter2] != 2)
     Handle_SyntaxError();
   instructionSet2[*instructionCounter2] += stringCheck(s);
}

Note: a more robust solution would assess the value of instructionCounter2 before using as an array index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top