You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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:

  1. Remove the trailing newline that fgets() automatically adds to each input string.
  2. Print everything after the first character of the word.
  3. Append the first character to the end of that output.
  4. 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 by fgets).
  • We strip the newline by replacing it with a null terminator, so we're only working with the actual word text.
  • string + 1 points directly to the second character of the string, so printf("%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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:45:02