Reputation: 21
I am unable to escape from the loop by entering newline.
int input(char str[], int n)
{
int ch, i = 0;
while ((ch == getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}
Upvotes: 1
Views: 551
Reputation: 910
Just replace ==
with =
because you want to assign getchar()
to ch
and not compare it.
int input(char str[], int n)
{
int ch, i = 0;
while ((ch = getchar()) != '\n'){
if (i < n)
str[i++] = ch;
}
str[i] = '\0';
return i;
}
Upvotes: 4
Reputation: 15042
(ch == getchar())
You use ==
instead of =
.
==
is used as boolean operator for checking if the left hand operand equals right hand one.
Thus, the loop will never terminate because you compare 0
or 1
(which is the result of (ch == getchar())
with \n
whose ASCII value is 10
.
That´s what the error is saying.
=
is used for assignment and required to assign the character fetched by getchar()
to ch
.
This is the corrected version:
while ((ch = getchar()) != '\n') {
if (i < n)
str[i++] = ch;
}
Upvotes: 0
Reputation: 823
Yo forgot {
symbols in your code. Any control structure such while
and if
of more than one instruction line should be coded like this :
while(condition){
instruction 1;
instruction 2;
...
}
By the way your i
is always 0 and your n
does not change within your function.
EDIT: The reason you obtain your warning have been answered by someone else.
Upvotes: 0