C语言字符串反转方案失效原因求助(含题目要求及部分代码)
Hey there! Let's figure out why your string reversal code isn't working as expected. First, let's recap the problem statement to make sure we're on the same page:
Write a function reverse (s) that reverses the character strings. Use it to write a program that reverses its input a line at a time
Your code got cut off at the while(len = ...) part, but I can walk through the most common pitfalls people hit with this problem, show you a working implementation, and explain how to fix typical issues.
Common Issues That Break String Reversal
Before diving into code, let's cover the mistakes that usually cause problems here:
- Missing null terminator: C strings rely on a
\0to mark the end. If yourngetlinefunction doesn't add this, your reversal logic orprintfwill read garbage memory. - Off-by-one errors: When swapping characters in the reverse function, it's easy to miscalculate the last index (using
leninstead oflen-1, for example). - Incorrect line reading: If your
ngetlineincludes the newline character (\n) in the string, reversing it will put the newline at the start of the line, leading to weird output. - Ignoring EOF: Your loop needs to handle the end-of-file condition properly to avoid infinite loops or unexpected behavior.
- Non-standard
mainfunction: Old C allowsmain()without a return type, but modern compilers will warn about this—always useint main()for portability.
Working Implementation
Here's a complete, tested version of the program that fixes these issues:
/*Write a function reverse (s) that reverses the character strings. Use it to write a program that reverses its input a line at a time*/ #include <stdio.h> #define MAXLENGTH 1000 // Reads a line into s, returns the length of the line (excluding newline) int ngetline(char s[], int lim) { int c, i; // Read characters until we hit newline, EOF, or reach the buffer limit for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) { s[i] = c; } // Uncomment the line below if you want to include the newline in the reversed string // if (c == '\n') s[i++] = c; // Critical: Add the null terminator to mark the end of the string s[i] = '\0'; return i; } // Reverses the string s using its length (avoids recalculating length inside the function) void nreverse(char s[], int len) { int start = 0; int end = len - 1; char temp; // Swap characters from the start and end, moving toward the center while (start < end) { temp = s[start]; s[start] = s[end]; s[end] = temp; start++; end--; } } // Standard main function with proper return type int main() { int len; char line[MAXLENGTH]; // Keep reading lines until ngetline returns 0 (EOF or empty line) while ((len = ngetline(line, MAXLENGTH)) > 0) { nreverse(line, len); printf("%s\n", line); } return 0; }
How to Adapt This to Your Code
If you want to stick with your original function signatures, here are key fixes to apply:
- Fix
ngetline: Make sure it adds the\0terminator and handles EOF correctly. If you want to exclude the newline (most people do for clean output), don't write it to the string. - Fix
nreverse: Use the line length to avoid off-by-one errors. If you don't want to pass the length, you can calculate it inside the function by looping until you hit\0:void nreverse(char s[]) { int len = 0; while (s[len] != '\0') len++; // Calculate string length int start = 0, end = len - 1; char temp; while (start < end) { temp = s[start]; s[start] = s[end]; s[end] = temp; start++; end--; } } - Fix the main loop: Use
while ((len = ngetline(line, MAXLENGTH)) > 0)to stop when EOF is reached.
Testing the Program
To test it, compile and run the code, then type a few lines of text. Press Ctrl+D (on Unix/macOS) or Ctrl+Z (on Windows) to trigger EOF. You should see each line reversed in the output.
内容的提问来源于stack exchange,提问作者BlankQQ

