私は 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;
}
どんな助けでも大歓迎です!事前に感謝します。さらに情報が必要な場合は、提供します。