我对 C 完全陌生,我正在开发一个程序,该程序必须从文本文件(两个数字和一个数学符号)中读取 3 行并写出结果。例如:
文本文件如下所示:
1
4
*
我的程序应该能够读取 3 行并写出类似“1 * 4 = 4”之类的东西。
我设法达到了可以读取 3 行并在屏幕上显示它们的地步,所以我想我应该将这两个数字放在一个数组中,将符号放在另一个数组中。问题是,我试图查看数组是否包含我放入其中的数字,而我的输出中有一些巨大的数字,我不知道为什么。
这是我写的代码:
#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;
}
任何帮助将不胜感激!提前谢谢您如果您需要更多信息,我会提供。