C:FileI / O循环遍历包含一组数字的文件,以查找它们的正方形,立方体和平方根

时间:2016-12-06 19:26:12

标签: c file-io

该程序的目标是从文本文件循环中读取一组数字,通过文件中的每个数字找到每个数字的Square,Cube和Square根,并在输出文本文件中写入新数字。

我已经弄清楚如何正确读取和写入文件,但我无法弄清楚如何正确格式化循环以从输入文件中读取每个数字。

我也尝试在math.h中使用“sqrt()”函数,但它无法正常工作我更关心的是首先让循环正常工作。

   #include <stdio.h>
   #include <ctype.h>
   #include <math.h>
   #define SIZE 40

  int main(void)
{
char ch, filename[SIZE]; //variables


int i, n, square, cube , sroot;

FILE *fp;
printf("Please enter the filename to read: ");
gets(filename);


if ((fp = fopen(filename, "r")) == NULL)
{
    printf("Cannot open the file, %s\n", filename);
}
else
{
    while (fscanf(fp,"%d",&n) == 1)
    {
      for(i=0; i<=n; i++)
      {

      square=n*n;
      cube=square*n;
      sroot= sqrt(n);
      }
}
}


fclose(fp);

char filename2 [SIZE];
FILE *fp2;

fprintf(stdout, "Please enter the file name to write in: "); //asks for file that you want to write to
gets(filename2);

if ((fp2 = fopen(filename2, "w")) == NULL) //"w" for writing
{
    printf("Cannot create the file, %s\n", filename2);
}
else
{
    for(i=0; i<=n; i++)
    {
        fprintf(fp2, "%d, %d, %d \n",square, cube, sroot);

    }

}

fclose(fp2); // closing the file
fprintf(stdout, "You are writing to the file, %s is done.\n", filename2);

return 0;

}

2 个答案:

答案 0 :(得分:1)

打开两个文件并检查是否成功。然后,当从输入文件中读取值时,将结果打印到输出文件。关闭这两个文件 使用fgets代替gets

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define SIZE 40

int main(void)
{
    char filename[SIZE] = {'\0'};
    char filename2 [SIZE] = {'\0'};
    int n = 0, square = 0, cube = 0 , sroot = 0;
    FILE *fp2;
    FILE *fp;

    printf("Please enter the filename to read: ");
    fgets ( filename, SIZE, stdin);
    filename[strcspn ( filename, "\n")] = '\0';//remove newline

    if ((fp = fopen(filename, "r")) == NULL)
    {
        printf("Cannot open the file, %s\n", filename);
        return 1;
    }

    printf( "Please enter the file name to write in: "); //asks for file that you want to write to
    fgets ( filename2, SIZE, stdin);
    filename2[strcspn ( filename2, "\n")] = '\0';//remove newline

    if ((fp2 = fopen(filename2, "w")) == NULL)
    {
        printf("Cannot open the file, %s\n", filename2);
        fclose ( fp);
        return 2;
    }

    while (fscanf(fp,"%d",&n) == 1)//read a number from input
    {
        square=n*n;
        cube=square*n;
        sroot= (int)sqrt((double)n);
        //print results to output
        fprintf(fp2, "%d, %d, %d \n",square, cube, sroot);
    }
    fclose(fp);
    fclose(fp2);
    printf( "You are writing to the file, %s is done.\n", filename2);
    return 0;
}

答案 1 :(得分:0)

C库函数fscanf() - https://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm

  

此函数返回成功匹配和分配的输入项的数量,可以少于提供的数量,或者在早期匹配失败时甚至为零。

循环不起作用,因为输入项​​的数量仅在第一次迭代时为1,之后它更多,因此它不会进入 while循环

如果这就是你想要它做的,那么在那里放置它是没有意义的,如果你想检查是否有任何东西可以从那个文件中读取,你可以简单地放一个if。否则,这可能是你的问题。