C语言字符串逆序输出问题求助:输出格式不符预期
Fixing Your Reverse Suffix Output Issue
Hey there! Let's break down why your code isn't giving you the expected output and fix it step by step.
The Problem Breakdown
You want to take a string like "Table" and output suffixes starting from the shortest (last character) to the full string, in their normal order, separated by spaces: "e le ble able Table".
Right now, your code is doing three things wrong:
- It prints each suffix in reverse order (hence
"e el elb elba elbaT"instead of the correct forward suffixes). - It doesn't add spaces between each suffix, so everything runs together.
fgetsincludes the newline character from your input, which could cause unexpected behavior if not handled.
The Fixed Code
Here's the adjusted code that produces your desired output:
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char str[100]; printf("Enter a string: "); fgets(str, 100, stdin); // Remove the newline character added by fgets size_t len = strlen(str); if (len > 0 && str[len - 1] == '\n') { str[len - 1] = '\0'; len--; } // Loop through each suffix length from 1 to full string length for (int i = 1; i <= len; i++) { // Calculate the starting index of the current suffix int start = len - i; // Print each character of the suffix in normal order for (int j = start; j < len; j++) { printf("%c", str[j]); } // Add a space after each suffix printf(" "); } printf("\n"); // Add a final newline for clean output return 0; }
Key Changes Explained
- Handling
fgetsnewline: We check if the last character is a newline and replace it with a null terminator. This ensures we're only working with the actual input string, no extra hidden characters. - Forward suffix printing: Instead of looping from the end of the string backwards, we calculate the starting index of each suffix (e.g., for length 2 in
"Table", start at index 3 which is 'l') and print characters from that start to the end of the string. - Space separation: After each suffix, we print a space to match your desired format.
Testing this with input "Table" will give you exactly: e le ble able Table
内容的提问来源于stack exchange,提问作者Kazizo
相关产品推荐
相关产品推荐

