问题
I am working through a problem in the C ansi programming book. I am asking the user for input until there is no end of line. However, i'd like to have the characters moved to the next line once 10 characters have been reached. However, the newline character only works after hitting enter. Shouldn't a new line be outputted once i == 10?
#include <stdio.h>
#define MAXLINE 10
// count number of chars, once it reaches certain amount
int main()
{
int i,c;
for (i=0;(c=getchar()) != EOF; i++)
{
if (c == '\n'){
i = 0;
}
else if (i == MAXLINE){
printf("\n");
}
}
//printf("%d\n",i);
}
Thank you.
回答1:
"Shouldn't a newline be outputted once
i == 10
?"
No. Because the console input is buffered by default. getchar()
will not return the next character in stdin
before it found a newline character '\n'
in stdin
. The newline is required to flush the buffer.
There are implementation-based solutions possible to flush the input immediately and not waiting for the newline. For example getche() in conio.h under Windows/DOS or the cbreak() option and using getch() instead of getchar()
in the curses-library for Linux.
Also your counting is incorrect, with i = 0;
and if (i == MAXLINE)
after 11 characters will a newline be placed in the output, not after 10. This is because you start at 0
, not 1
. Use either i = 1
or if (i == (MAXLINE - 1))
instead.
If you are on Windows/DOS, try:
#include <stdio.h>
#include <conio.h> // Necessary to use getche().
#define MAXLINE 10
// count number of chars, once it reaches certain amount
int main (void)
{
int i, c;
for (i = 0; (c = getche()) != EOF; i++)
{
if (i == (MAXLINE - 1))
{
printf("\n");
i = -1; // Counter is reset. To break out of the loop use CTRL + Z.
}
}
//printf("%d\n",i);
}
If the counter reset is a bit hard to understand for you, the code above is basically equivalent to:
#include <stdio.h>
#include <conio.h> // Necessary to use getche().
#define MAXLINE 10
// count number of chars, once it reaches certain amount
int main (void)
{
int i, c;
for (i = 1; (c = getche()) != EOF; i++)
{
if (i == MAXLINE)
{
printf("\n");
i = 0; // Counter is reset. To break out of the loop use CTRL + Z.
}
}
//printf("%d\n",i);
}
For Linux use the cbreak()
and getch()
from the ncurses-library:
#include <stdio.h>
#include <ncurses.h>
#define MAXLINE 10
// count number of chars, once it reaches certain amount
int main (void)
{
cbreak();
echo();
initscr();
int i, c;
for (i = 1; (c = getch()) != ERR; i++)
{
if (i == MAXLINE)
{
printf("\n");
refresh();
i = 0; // Counter is reset. To break out of the loop use CTRL + D.
}
}
//printf("%d\n",i);
endwin();
}
Note: To use the ncurses-library, you need to add the -lnurses
option at invoking the compiler.
Furthermore, you need to use initscr()
and endwin()
to open and close the curses terminal window.
来源:https://stackoverflow.com/questions/62030332/how-to-fold-input-when-max-character-limit-is-reached