-1

I have this program that create a new line after every 10 characters. However, once it hits the second iteration and there after it only outputs 9 characters. The program works if I set the second i to -1 but I do not understand why it will not work with i set to 0. The logic is the exact same as the first run as the first i is only run once, so when I want a new line I reset i. Can someone explain what I am missing? I drew out the steps on paper but it still doesn't make sense. Thank you.

enter image description here

#include <stdio.h>
#include <ncurses.h>            

#define MAXLINE 10


// count number of chars, once it reaches certain amount
int main (void) 
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = 0;          // Counter is reset. To break out of the loop use CTRL + D.
         }
    }

    // to close curses terminal
    endwin();
}
Colorful Codes
  • 577
  • 4
  • 16
  • The `printf` won't work properly with curses, since *stdout* stream and ncurses don't necessarily flush at the same point. – Thomas Dickey May 30 '20 at 23:36

3 Answers3

1

The first time through the loop i is zero. When you set i to zero inside the loop, when control reaches the end of the for, the statement executed is i++ (making i 1), then (c = getch()) != EOF

pmg
  • 106,608
  • 13
  • 126
  • 198
1

The first iteration starts with i set to zero. When the test in the loop resets i to zero, the usual execution of i++ in the for loop still occurs, so the next iteration has i set to one, not zero.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

You seem to intermixed both of my examples of my previous answer to your previous question.

Unfortunately, It seems that I didn´t pointed out the reset explicitly although I hinted the difference. I apologize.

The reset needs to be 1 less than the initial start value of the counter because the counter gets incremented at the end of the loop in which the reset takes place, although the incrementation should be only valid for every fully next iteration. We need to make it one integral value less to compensate this effect.

In your actual code, You need to replace i = 0; with i = -1 as seen in one of the examples in my previous answer.


Furthermore, the commenting of cbreak() isn´t a good idea as the console can be either in cbreak() or nocbreak() mode when the program is started up (it is not fixed). Use the explicit cbreak() to determine that the input will immediately read by characters, without the wait for a newline character to flush the buffer.

The Linux man page says:

"Initially the terminal may or may not be in cbreak mode, as the mode is inherited; therefore, a program should call cbreak or nocbreak explicitly."