#include <stdio.h>
#define MAXLENGTH 77
int getline(char[], int);
main() {
char in_line[MAXLENGTH];
int count, in_line_length;
in_line_length = 0;
for (count = 0; count < MAXLENGTH; ++count)
in_line[count] = 0;
in_line_length = getline(in_line, MAXLENGTH);
printf("%s", in_line);
}
int getline(char line[], int max_length) {
int count, character;
character = 0;
for (count = 0; count < (max_length -2) && (character = getchar()) != EOF && character != '\n'; count++) {
line[count] = character;
}
if (character = '\n') 开发者_开发知识库{
line[count++] = '\n';
}
line[count] = '\0';
return count;
}
I'm having a peculiar issue with the above code. As a little background, I'm compiling the above C code with the Tiny C Compiler (TCC) and running the executable in a Windows XP command prompt (cmd.exe
).
The problem that appears to be occuring has to do with the EOF
character. When running, if I issue the EOF
character (CTRL+Z
) and then hit return, the loop seems to exit correctly, but then character
is populated with a newline character (\n
).
So, something like this (as input):
test^Ztesttwo
Would output:
test\n
Due to the fact that the if statement
following the for loop
is always executed. What I'm wondering, is why the loop successfully exits upon recognition of the EOF
character if it continues to grab another character from the stream?
Your problem is this line:
if (character = '\n') {
it is an assigment instead of a test operator:
if (character == '\n') {
You can prevent erros like this by putting the constant left, that way you will get a compiler error if you make a mistake.
if ('\n' = character) {
// ^ wont compile
精彩评论