Pregunta

I'm completely new to C and I'm working on a program which has to read in 3 lines from a text file(two numbers and a mathematical symbol) and write out the result. So for example:

The text file looks like:

1

4

*

and my program should be able to read the 3 lines and write out something like "1*4 = 4" or something.

I managed to get to a point where i can read the 3 lines in and show them on screen, so I thought I should put the two numbers in one array and the symbol in another one. The problem is, that I tried to see if the arrays contain the numbers I put in them and my output has some huge numbers in it and I'm not sure why.

Here's the code i wrote:

#include <stdio.h>
#include <io.h>
#include <string.h>

    int main(void)
    {
        int res = 1;                                /*Creates an integer to hold the result of the check for the file*/
        const char *file = "input.txt";             /*String holding the name of the file with the input data*/

        res = access(file,R_OK);                    /*Checks if the file "input.txt" exists*/

        if(res == -1)
        {                                           /*IF the file doesn't exist:*/
            FILE *input = fopen("input.txt","w");   /*This creates a file called "input.txt" in the directory of the program*/
            char write[] = "1\n1\n+";               /*This variable holds the string that's to be written to the file*/
            fprintf(input,"%s",write);              /*This writes the variable "write" to the file*/
            printf("input.txt file created!");      /*Tells you the file is created*/
            fclose(input);                          /*Closes the file after it's done*/
        }
        else
        {                                           /*IF the file exists:*/
            FILE *f = fopen("input.txt","r");

            //char line[ 5000 ];
            //while ( fgets ( line, sizeof line, f ) != NULL )
            //{
            //    fputs ( line, stdout );
            //}

            char line[5000];
            char nums[2];
            char symbol[1];

            int i = 0;
            while(fgets(line,sizeof line,f)!=NULL)
            {
                i++;
                if(i < 3)
                {
                    fputs(nums,f);
                }
                else
                {
                    fputs(symbol,f);
                }

                printf("%d,%d",nums,symbol);
            }

            printf("\n\n\n");
            scanf("\n");
        }

        return 0;
}

Any help would be greatly appreciated! Thank you in advance If you require any more information i will provide it.

¿Fue útil?

Solución 2

What are you reading from the files are simply characters codes: the program has no way of figuring by itself that the character "4" corresponds to the integer number 4. The %d placeholder of printf expects int variables, or it won't work.

If you want just to print the characters you have to save them in char variables (or a char array) and use the placeholder %c in printf. If you want to actually use the numbers and symbols in your program you have more work to do.

Not only in C, but I think in most languages you have to "parse" the characters to numbers.

In C you can use the functions atoi or atol (you have to #include <stdlib.h>) in order to do this conversion.

In order to parse the symbol I'm afraid you will have to use an if or a switch to read the character and perform the operation accordingly.

For example your loop could look like:

  while(fgets(line,sizeof line,f)!=NULL)
    {
      int op1;
      int op2;
      int res;
      char symbol;
      i++;
      switch (i) {
        case 1:
          //First line is first operand
          op1 = atoi(line);
          printf("op1 %d\n",op1);
          break;
        case 3:
          //Second line is second operand
          op2 = atoi(line);
          printf("op2 %d\n",op2);
          break;
          //Fifth line is the operator, could be +,-,%./ or anything
        case 5:
          symbol = line[0];
          printf("operand %c\n",symbol);
          switch(symbol) {
            case '+':
              res = op1+op2;
              break;
            case '-':
              res = op1-op2;
              break;
            default:
              //operation not defined, return
              return;

          }
          printf("%d%c%d = %d",op1,symbol,op2,res);
      }
    }

Otros consejos

This is a self-explanatory algorithm. Also, here is the code that does the operation you are looking for. Generally, the complex operations are accomplished using stack, push and pop method. Once the operators are pushed. One need to apply the BODMAS rule,to evaluate the expression. Since the problem given to you is simple, a simple expression evaluation. This can be simply achieved by FIFO. Here is the algorithm, general explanation. Afterwards, the code is present. This code is well tested.You can extend it to do operations like +,-,division /, %, etc. If you like my answer please appreciate.

enter image description here

#include "stdio.h"

int main(int argc, char *argv[])
{

  FILE *fp_op;

  int buff[2]; /** assuming a simple operation, thus the buffer size is 3 only, the last one is to store the NULL **/

  char operat_buff[2]; /** assuming this operation we can extend it to evaluate an expression **/

  fp_op = fopen("calc.txt","rb");

  if ( fp_op == 0 )
  {
     perror("The file doesn't exist to calculate\r\n");

     goto error; 

  }


 /** Read the two numbers here **/
 fscanf(fp_op,"%d",&(buff[0]));

 printf("The buff[1] = %d\r\n",buff[0]);

 fscanf(fp_op,"%d",&(buff[1]));

 printf("The buff[1] = %d\r\n",buff[1]);


  /** read the next line now \n **/

  operat_buff[0] = fgetc(fp_op);

  /** read the actual character now **/

   operat_buff[0] = fgetc(fp_op);

  printf("The operat_buff[0] = %d\r\n",operat_buff[0]);

 /** Read operation completed **/

 /** use switch here **/


  switch(operat_buff[0])
  {
    case '*':

      printf("The multiplication result=%d\r\n",buff[0]*buff[1]);
      break;

    case '+':
       printf("The Addition result=%d\r\n",buff[0]+buff[1]);
      break;

    default:

      printf("Add more operations\r\n");

  }

  return 0;

 error:
       return -1;


}

I assume that the calc.txt was something like this.

calc.txt

3
5
*

Note: This code is compiled and verified.It compiles with zero warnings. It does the error checking too. You can directly copy and paste it.

printf("%d,%d",nums,symbol);

In your code nums and symbol are strings, you can't print them with %d. What you are getting are the addresses of the nums and symbol arrays, respectively - even if that's not the right way of printing an address.

You'll likely want to convert them to integers, using strtol or sscanf and then use those to perform the computation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top