Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 18 additions & 13 deletions chapter_2/exercise_2_02/loop.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,35 @@

int main(void) {
char s[MAXLINE];
int c, i = 0;

// int i;
// int c;
// for (i = 0; (i < MAXLINE - 1) * ((c = getchar()) != '\n') * (c != EOF);
// ++i)
// int i, c;
// for (i = 0; (i < MAXLINE - 1) * ((c = getchar()) != '\n') * (c != EOF); ++i)
// {
// s[i] = c;
// }

int i = 0;
int loop = 1;
while (loop) {

while (1) {
if (i >= MAXLINE - 1){
break;
}

char c = getchar();

if (i >= (MAXLINE - 1) || c == '\n' || c == EOF) {
loop = 0;
if (c == '\n'){
break;
}

s[i++] = c;
else if (c == EOF){
printf("\n");
break;
}
Comment on lines +27 to +30
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Questionable: Extra newline printed on EOF.

Lines 25-28 print a newline when EOF is encountered, but not for other exit conditions (newline or buffer full). This creates inconsistent output behavior.

Consider whether this extra newline is necessary or if EOF should be handled like the newline case (just break).

🤖 Prompt for AI Agents
In chapter_2/exercise_2_02/loop.c around lines 25 to 28, the code prints an
extra newline when c == EOF which causes inconsistent output compared to other
exit conditions; remove the printf("\n") so EOF is handled the same as the
newline/buffer-full cases (just break), or restructure the branch to break
immediately on EOF without emitting any characters.

else
s[i++] = c;
}

s[i] = '\0';

printf("%s", s);
printf("%s\n", s);

return 0;
}
Expand Down