B1FF语言转换程序无输出排查:两段相似C代码差异分析
Hey there! Let's break down exactly why your do-while version isn't working, compared to the functional for loop. The core issue is a off-by-one error in how you're checking the loop condition—you're looking at the wrong array index entirely.
First, Let's Recap the Working For Loop
The code that works has a tight, logical flow:
for(;(message[len] = getchar()) != '\n';) len++;
Here's what it does step-by-step:
- Reads a character with
getchar()and stores it directly intomessage[len]. - Checks if that stored character is not a newline (
'\n'). - If it's not a newline, increments
lenand repeats. - When it hits a newline, it stores the newline in
message[len], then the condition fails (since'\n' == '\n'), so the loop stops—without incrementinglen.
Now Let's Diagnose Your Broken Do-While Loop
Your loop has a critical order issue:
do { message[len] = getchar(); len++; } while (message[len] != '\n');
Here's where it goes wrong:
- After storing the character in
message[len], you immediately incrementlen. - Next, you check
message[len]—the next, uninitialized index in the array—to see if it's a newline. This index holds random garbage (since it's uninitialized stack memory), so the condition will almost never be true. - The loop runs forever: it keeps reading characters, incrementing
len, and checking meaningless values. Your program gets stuck here, never reaching the code that converts and prints your B1FF message.
Fixed Do-While Loop
You need to check the character you just stored, not the empty next spot. Here's a corrected version that matches the working for loop's logic (plus a safety check to prevent array overflow):
do { message[len] = getchar(); // Stop if we hit a newline (don't increment len in this case) if (message[len] == '\n') { break; } len++; // Prevent writing past the end of the array } while (len < N - 1);
Or another clean way to structure it, which avoids redundant checks:
int c; len = 0; do { c = getchar(); // Stop if we hit a newline or run out of array space if (c == '\n' || len >= N - 1) { break; } message[len++] = c; } while (1);
Bonus: Avoid Array Overflow
Both your original do-while and the working for loop have a hidden risk: if the user enters more than N-1 characters, you'll write past the end of the message array, causing undefined behavior. Adding the len < N-1 check fixes this.
内容的提问来源于stack exchange,提问作者Yaim

