473,399 Members | 2,858 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Handling User's Input

der
Hello all,

I want to use fgets() to read lines.
Now, if the user has entered more characters than it was supposed to,
the next call to fgets() would read
these characters, which I don't want to be read, but rather
reading fresh new line instead.

How should I deal with such scenario?

Here is my way of solving this problem.
I would like to know what you think about it.

void
getline(char *s, int size)
{
int len;
int correct_input;

do {
correct_input = 1;
fgets(s, size, stdin);
len = strlen(s);
if (len == size-1 && s[len-1] != '\n') {
/* if we have read size-1 characters, and the next
* one was '\n', delete it from stdin's buffer, and
* exit the loop.
*/
if (getchar() == '\n')
break;
/* If we are here, we have read too many characters.*/
correct_input = 0;
while (getchar() != '\n')
;
}
if (!correct_input)
printf("line is too big, please enter shorter"
" line.\n");
} while (!correct_input);
}

Thanks in advance,

der
Nov 13 '05 #1
2 5058
der
Irrwahn Grausewitz wrote:
der <de*@noemail.com> wrote in <3f******@news.012.net.il>:
Hello all,

I want to use fgets() to read lines.
Now, if the user has entered more characters than it was supposed to,
the next call to fgets() would read
these characters, which I don't want to be read, but rather
reading fresh new line instead.

How should I deal with such scenario?

Here is my way of solving this problem.
I would like to know what you think about it.

<CODE EXAMPLE SNIPPED>

Your code seems to work (I haven't tested it thoroughly).

I personally like another approach:

- use a dynamically allocated input buffer, so you
can adjust it's size if necessary
- read input on a char-by-char basis with fgetc()
into your buffer

This way you've got full control over input handling and dealing
with newline / EOF / error conditions is very easy. I admit that
basically this means you have to write your own fgets() funtion,
but besides being a good exercise you have the advantage that you
can easily change it to suit your needs (for example if you want
to split up input on certain characters received). And it may be
shorter as your code as well...


Thanks for pointing this out.
I will use this strategy too.
Just be aware, that if you access the buffer via a static pointer
local to your function, you have to copy the result before the
next time your function is called!


Yes, of course.

Thanks for your help,

der
Nov 13 '05 #2
On Sun, 17 Aug 2003, der wrote:
Hello all,

I want to use fgets() to read lines.
Now, if the user has entered more characters than it was supposed to,
the next call to fgets() would read
these characters, which I don't want to be read, but rather
reading fresh new line instead.

How should I deal with such scenario?
Two ways come to mind. The first is to read in a fixed length and then
toss away anything that exceeds that length for a given line. The second
is to grow the buffer until it is big enough to hold whatever length the
user input.

For the first method, use an fgets to read what you want to keep. If the
last character is not a '\n' then you know there is more to get. You then
want a function that gets and discards the input until '\n' is reached.
Something like:

fgets the line you want
while(more line left)
fgets more into temporary buffer

For the second solution I would use:

allocate a buffer of size XXX
fgets into &buffer[0]
while(more line left)
realloc buffer to XXX += XXX
fgets into &buffer[XXX]

So you just keep tacking on to the end of the newly resized buffer.
Here is my way of solving this problem.
I would like to know what you think about it.

void
getline(char *s, int size)
{
int len;
int correct_input;

do {
correct_input = 1;
fgets(s, size, stdin);
len = strlen(s);
if (len == size-1 && s[len-1] != '\n') {
You could also search the string for a '\n'. If it does not exist then you
have the same situation but it is only one comparison.
/* if we have read size-1 characters, and the next
* one was '\n', delete it from stdin's buffer, and
* exit the loop.
*/
if (getchar() == '\n')
break;
/* If we are here, we have read too many characters.*/
correct_input = 0;
while (getchar() != '\n')
;
Getting one character at a time is not the most efficient way to clear the
buffer. Since you are going to prompt the user for input again, just use:

do {
fgets(s, size, stdin);
while(strchr(s, '\n') == NULL);
}
if (!correct_input)
printf("line is too big, please enter shorter"
" line.\n");
} while (!correct_input);
}

Thanks in advance,

der


--
main(){int j=1234;char t[]=":@abcdefghijklmnopqrstuvwxyz.\n",*i=
"iqgbgxmdbjlgdv.lksrqek.n";char *strchr(const char *,int);while(
*i){j+=strchr(t,*i++)-t;j%=sizeof t-1;putchar(t[j]);} return 0;}

Nov 13 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Master of C++ | last post by:
Hi, I am writing a simulation package in C++, and so far I've written about 8000 lines of code and have about 30 classes. I haven't used C++ exceptions so far (for various reasons). The only two...
12
by: Christian Christmann | last post by:
Hi, assert and error handling can be used for similar purposes. When should one use assert instead of try/catch and in which cases the error handling is preferable? I've read somewhere that...
4
by: John Fereira | last post by:
So, one of the limitations of multipart-form handling is that when an <input type="file" ..> tag is used it will bring up a window which allows a user to select a file for upload but won't allow...
7
by: Spacen Jasset | last post by:
The main two desirable things I feel error handling should provide are these: 1) Debugging and diagnostic aid 2) User feedback One method that is used a fair amount it to 'say' that all...
1
by: EricRybarczyk | last post by:
I am starting a rewrite of an existing Classic ASP web site in ASP.NET 2.0. The existing ASP application has several types of users, each with a separate login process (separate login page,...
5
by: csgraham74 | last post by:
Hi guys, Basically i have been developing in dotnet for a couple of years but ive had a few issues in regards to error handling. For example - I have a class that i call passing in a stored...
12
by: sam | last post by:
hi all, i'm starting to put together a program to simulate the performance of an investment portfolio in a monte carlo manner doing x thousand iterations and extracting data from the results. ...
35
by: jeffc226 | last post by:
I'm interested in an idiom for handling errors in functions without using traditional nested ifs, because I think that can be very awkward and difficult to maintain, when the number of error checks...
8
by: JWest46088 | last post by:
I'm having problems with my error handling. It's kind of hard to explain so I'll just post my code and bold where the error handling is and then explain what is happening. Just to warn you, I am...
9
by: Josh | last post by:
I run a Joomla website and am familiar with php in some but not all aspects. Currently I am trying to find some solutions related to session handling. Am I correct in saying that "login" is kept...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.