如何修改C语言程序实现单词首字母移至末尾的功能?
Fixing Your Word Rotation Program
Let's break down what's going wrong with your current code and how to fix it to move the first letter to the end of each word.
What's Wrong with the Original Code
Your current logic tries to output characters starting from index 1, and only prints the first letter if it hits a newline mid-loop. This leads to two key issues:
- The first letter only gets printed in a narrow edge case, which doesn't work consistently for all your input words.
- You end up printing an extra newline at the end of each iteration, creating unnecessary blank lines in the output.
The Simplified Fix
Instead of manually looping through each character (which is error-prone), we can streamline the logic with these steps:
- Remove the trailing newline that
fgets()automatically adds to each input string. - Print everything after the first character of the word.
- Append the first character to the end of that output.
- Add a newline to match your desired output format.
Here's the revised code:
#include <stdio.h> #include <string.h> // Required for strlen() #define BUFFER_SIZE 81 int main(int argc, char **argv) { char string[BUFFER_SIZE]; while(fgets(string, BUFFER_SIZE, stdin) != NULL) { // Get the length of the input string size_t len = strlen(string); // Clean up the trailing newline character from fgets if (len > 0 && string[len - 1] == '\n') { string[len - 1] = '\0'; len--; // Adjust length to exclude the newline } // Skip empty lines (though your input shouldn't have any) if (len > 0) { // Print all characters starting from the second one printf("%s", string + 1); // Print the first character at the end of the word putchar(string[0]); // Add a newline for the rotated word putchar('\n'); } fflush(stdout); } return 0; }
How This Works
strlen(string)gives us the full length of the input (including the newline added byfgets).- We strip the newline by replacing it with a null terminator, so we're only working with the actual word text.
string + 1points directly to the second character of the string, soprintf("%s", string + 1)prints the entire word except the first letter.- We then print the first character (
string[0]) to append it to the end of the truncated word. - Finally, we add a newline to ensure each rotated word appears on its own line.
Testing It
When you run ./RotateWord < flip.txt, this code will output exactly what you're looking for:
ackpackb arpetc otater
内容的提问来源于stack exchange,提问作者NotHungry2Phil
相关产品推荐
相关产品推荐

