How to remove the trailing space at the end of a line when using fprintf in c++

334 Views Asked by At

I am trying to write to file a set of integer from 1 to 640 (with fixed width=8) without use of newline. When i scroll across each row (take row1), there is a space left (for fixed width=8) at the end of the row as shown in the image. When the cursor is moved from beginning of one integer to that of the next, the column value increments by 8.

I need the cursor to jump to the next row immediately after the last integer in that row (i.e 16 in first row) has been crossed (i.e without extra space as in the image). I also need that the column value should still increment by 8 at the beginning of the next row. That is the column value should be 15X8+1=121 before the integer 16, after the integer 16 it should be 15X8+3=123, then cursor should jump to next row showing a column value of 16X8 + 1=129.

My code is below the image. (The column value for the cursor is shown at the bottom right in gedit or other text editors) enter image description here

#include <iostream>     // std::cout, std::endl
#include <iomanip>      // std::setw
#include <stdio.h>
#include <stdlib.h>

int main () {
    
   FILE * fp;    
   fp = fopen ("file.txt", "w+");

   int n=640;
   for(int i = 1; i <= n; i++)
   {
      fprintf(fp, "%-8d", i);
   }

   fclose(fp);

   return 0;
}
1

There are 1 best solutions below

7
BingShan Wang On

it is easy , you need add a judge.

#include <iostream>     // std::cout, std::endl
#include <iomanip>      // std::setw
#include <stdio.h>
#include <stdlib.h>

int main () {
    
   FILE * fp;    
   fp = fopen ("file.txt", "w+");

   int n=640;
   for(int i = 1; i <= n; i++)
   {
      fprintf(fp, "%d ", i);  //fix printf
      if(i % 8 == 0){       //add a if judge
          fprintf(fp,"\n");   
      }
   }

   fclose(fp);

   return 0;
}