0

私は C がまったく初めてで、テキスト ファイルから 3 行 (2 つの数字と数学記号) を読み取って結果を書き出す必要があるプログラムに取り組んでいます。たとえば、次のようになります。

テキスト ファイルは次のようになります。

1

4

*

私のプログラムは3行を読み取って、「1 * 4 = 4」などのように書き出せるはずです。

3行を読み取って画面に表示できるようになったので、2つの数字を1つの配列に、記号を別の配列に配置する必要があると考えました。問題は、配列に入力した数値が含まれているかどうかを確認しようとしたことと、出力に巨大な数値が含まれていることです。その理由はわかりません。

ここに私が書いたコードがあります:

#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;
}

どんな助けでも大歓迎です!事前に感謝します。さらに情報が必要な場合は、提供します。

4

3 に答える 3

2

これは自明のアルゴリズムです。また、探している操作を実行するコードは次のとおりです。一般に、複雑な操作は、スタック、プッシュ、およびポップ メソッドを使用して実行されます。オペレーターがプッシュされたら。式を評価するには、BODMAS ルールを適用する必要があります。出題する問題は簡単なので、簡単な式評価。これは、FIFO によって簡単に実現できます。これがアルゴリズム、一般的な説明です。その後、コードが表示されます。このコードは十分にテストされています。拡張して +、-、除算 /、% などの操作を実行できます。私の回答が気に入ったら、よろしくお願いします。

ここに画像の説明を入力

#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
*

注: このコードはコンパイルおよび検証済みです。警告なしでコンパイルされます。エラーチェックも行います。直接コピーして貼り付けることができます。

于 2013-09-25T08:56:27.347 に答える
1
printf("%d,%d",nums,symbol);

あなたのコードではnumssymbolは文字列で、 でそれらを印刷することはできません%d。あなたが得ているのは、それぞれnumssymbol配列のアドレスです - それがアドレスを印刷する正しい方法ではない場合でも。

strtolまたはを使用してそれらを整数に変換し、それらをsscanf使用して計算を実行することをお勧めします。

于 2013-09-24T19:47:55.217 に答える
1

ファイルから読み取っているのは、単なる文字コードです。プログラムは、文字「4」が整数 4 に対応することを自分で判断する方法がありません。printf の %d プレースホルダーは int 変数を想定しているか、機能しません。 .

文字を印刷するだけの場合は、それらを char 変数 (または char 配列) に保存し、printf でプレースホルダー %c を使用する必要があります。プログラムで数字と記号を実際に使用したい場合は、さらに作業が必要です。

C だけでなく、ほとんどの言語では、文字を数値に「解析」する必要があると思います。

#include <stdlib.h>Cでは、この変換を行うために関数 atoi または atol (必要があります) を使用できます。

シンボルを解析するには、if またはスイッチを使用して文字を読み取り、それに応じて操作を実行する必要があります。

たとえば、ループは次のようになります。

  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);
      }
    }
于 2013-09-24T20:16:49.193 に答える