You are here:

C/Reading line from the standard console

Advertisement


Question
Hi Sir:

I was trying to read a line from the standard in put console with the string limited by the length parameter. I have predefined skeleton of the function void getline(char *buf, size_t len), so here i have to read line of string into buf but when i enter string which is greater then len, next time i call function it seems it automatically takes the string from 10 to end of the string which i entered before and is unwanted , i tried flushing buffer by the fflush(stdin) but still its not working, can you please tell me another method of dong that?

Answer
Hi.

The problem you're seeing is a very common problem experience by beginners.  It has to do with the way input is handled.  It's a buffered input, and when you do not use the entire buffer, what's left ends up being used the next time an input request is made.  The common, simple way to get around this is to use a line of code that eats the rest of the buffer:

   while (getchar() != '\n');

This little line of code will read one character at a time from the buffer until it reaches a newline character (which is inserted in the buffer when you press return).  If you call that at the end of your getline function, it will empty the rest of the buffer and you should be able to continue reading input normally.

OK, I hope that helps.  If you have any further questions, please do not hesitate to ask.  I'm here to help. :)

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2012 About.com, a part of The New York Times Company. All rights reserved.