当 printf 打印我想要的行数时,freopen 只打印一行 (C++)

freopen only prints one line when printf prints as much lines as i want (C++)

所以我想将几行 GL 的 Vertex2d 坐标打印到一个文件中,我使用了这个:

{
   //namespace (for cout + cin)
   using namespace std;

   int p; //number of sides

   //body
   double r,d=3/4.0;

   cout << "input side count" <<endl;
   cin >> p;
   cout << "input radius" <<endl;
   cin >> r;

   FILE *fp;

   int i=0;
   double x,y,t;
   while(i<p)
   {
      t=2*M_PI*((double)i/p+d);
      x=cos(t)*r;
      y=sin(t)*r;

      if((fp=freopen("PTRON", "w" ,stdout))==NULL) {
         printf("Cannot open file.\n");
         exit(1);
      }

      printf("glVertex2d(%f, %f);\n",i,x,i,y);

      i++;
   }
   fclose(fp);
}

但它只在文件中打印了一行,看起来像这样;

glVertex2d(-0.406737, -0.913545);

虽然在控制台中它会打印所有行,如下所示:

glVertex2d(-0.406737, -0.913545);
glVertex2d(0.591057, -0.309017);
glVertex2d(0.587785, 0.80197);
glVertex2d(-0.687785, 0.809017);
etc.

为什么要这样做?我需要所有这些稍后将它们导入程序的 OpenGL 部分,以便它绘制具有所需半径和边数的多边形

我知道不应该是 glVertex2d( 0.0, 0.0 );但是还有一些其他的东西,但是我没有说到这很重要。

将以下行移到 while 循环之外。

  if((fp=freopen("PTRON", "w" ,stdout))==NULL) {
     printf("Cannot open file.\n");
     exit(1);
  }

我不知道 freopen 在程序中多次使用它时的行为是什么。

使用:

   if((fp=freopen("PTRON", "w" ,stdout))==NULL) {
      printf("Cannot open file.\n");
      exit(1);
   }

   while(i<p)
   {
      t=2*M_PI*((double)i/p+d);
      x=cos(t)*r;
      y=sin(t)*r;

      printf("glVertex2d(%f, %f);\n",i,x,i,y);

      i++;
   }