85249

How to fold input when max character limit is reached?

<h3>Question</h3>

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.


<h3>Answer1:</h3>
<blockquote>

"<em>Shouldn't a newline be outputted once i == 10?</em>"

</blockquote>

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.

<hr />

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); } <hr />

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(); }

<em>Note: To use the ncurses-library, you need to add the -lnurses option at invoking the compiler.</em>

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

Recommend

  • File format or File extension not valid
  • Near matches not found in CONTAINSTABLE
  • Cannot update/delete Firestore field with “period” in the name
  • How to use BigInteger in VS 2010
  • Python: BaseHTTPRequestHandler - Read raw post
  • AIrflow - Splitting DAG definition across multiple files
  • R: use min() within dplyr::mutate()
  • Perl Multithread Program
  • Service Fabric - How to reserve or protect my hardcoded Port
  • Java - localhost root folder?
  • Where to findViewById in a Drawer MainActivity?
  • Oracle SQL - get number of days between two dates for a specified month
  • What is a better way to implement a system wide side panel (similar to navigation drawer) in Android
  • How to handle extraction of double type numbers from a complex input (string) [duplicate]
  • Passing a list of parameters into a Python function [duplicate]
  • Saved Core Data does not persist after app closes 80% of the time
  • Why use 4096 elements for a char array buffer?
  • XCUITest: Running tests across two apps in a coordinated fashion
  • Role Count using Graph Api against a tenant
  • Selenium can't locate iframe
  • ClientRequest, how to serialize POJO's to json data correctly? could not find writer for conten
  • Hide legend for a single geom in ggplot2
  • integrity constraint violation: NOT NULL check constraint
  • Tensorflow crash using tf.train.Saver() with GPU
  • Modifying native query cannot have named parameter bindings?
  • Adding native code to an existing Worklight hybrid app
  • Swift manually rotate view controller
  • Julia 1.0 UndefVarError - Scope of Variable
  • How to use array in autohotkey?
  • Generate and export point cloud from Project Tango
  • How to check if a database and tables exist in sql server in a vb .net project?
  • java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/SpringDispatcher-ser
  • Tensorflow Dataset API restore Iterator after completing one epoch
  • Error handeling in antlr 3.0
  • How to turn off notice reporting in xampp?
  • reshape/remould data frame to create normalized bar chart and pie chart
  • Google App Engine Datastore: Dealing with eventual consistency
  • Accessing Arguments, Workflow Variables from custom activities
  • WPF custom control and direct content support
  • ReferenceError: TextEncoder is not defined