Taking a few characters of user input in c

L337Llama

Senior member
Mar 30, 2003
358
0
0
I'm writing a program that will take 5 characters the user inputs. The characters get compared, and a if the word matches anything, a message is printed out. It's being implemented in c.

Originally,I was using fgets and having setting the limit to the characters I needed. However, this caused a few problems.

fgets(inputStr, OP_LEN + 1, stdin);

So, it'd take the input and save the characters to the string. If the user input was longer than op_len, then it'd keep running the comparisons on the input in chunks that are the length of op_len.

Like, if the input bobloblawblog

then it would compare boblo, blawb, log\n instead of just looking at boblo and ignoring the rest.

So im changing it to use a loop of getchar, like this:

int charv = 0;
int loopvar = 0;
int count = 0;

while (loopvar = 0)
{
charv = getchar();
if ((count < OP_LEN + 1) && (charv != LF) && (charv != EOF))
{
inputStr[count] = charv;
}
else
{
loopvar = 1;
inputStr[count + 1] = 0;
}
count++;
}

Afterwords, the comparisons are made and a loop restarts to take the inputs and start over. That part works when fgets. However, when I changed the input to be taken with the above, it never actually gets anything and loops nonstop. Can anybody help me with what I am doing wrong?
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
I can't explain the loops forever part, because it shouldn't loop even once.

while( loopvar = 0 ) {}

Should be...

while( loopvar == 0) {}

In the first case you will get an assignment of 0 to loopvar first, and the result of the final evaluation should be 0, or false, and the loop should exit.

You can help prevent this type of error by reversing your terms...

while( 0 == loopvar ) {}

Since the literal '0' is not an lvalue, and can't be written to, should you do what you did above and accidentally assign to it you will get a compile-time error.

This might not be your whole problem, but it is a problem :).
 

L337Llama

Senior member
Mar 30, 2003
358
0
0
*smacks face*

I feel foolish for completely missing the == instead of =, but that fixed it. Thanks for showing me that.
I fixed it so now it's
while (loopvar == 0)
{
charv = getchar();
if (count < (OP_LEN + 1) && charv != 10 && charv != EOF)
{
inputStr[count] = charv;
}
else
{
loopvar = 1;
inputStr[count] = 0;
}
count++;
}

However, this ends up exhibiting the same behavior as using fgets. I'm trying to find a way to just read the first 5 characters of the user's input, so if they type applepie into stdin, all thats get saved is apple. This saves apple, runs the comparisons, and then saves le, and runs the comparisons instead of dropping the le. The only difference is this code ignores LF while fgets saves LF into the char array.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
Try read() instead of fgets(). To get stdin's file descriptor, use fileno().