使用 fgets 读取字符串,无法获取第二个字符串的输出

Reading a string using fgets, couldn't get output of second string

您没有在循环体中将 str_len 重置为 0。第二个字符串的长度不正确,因此第二个字符串没有正确反转。将循环更改为:

for (str_len = 0; S[str_len] != '[=10=]'; str_len++)
    continue;

请注意,您应该在反转字符串之前去除尾随 '\n'。您可以在计算 str_len.

之前使用 S[strcspn(S, "\n")] = '[=15=]'; 执行此操作

这是使用 scanf() 的简化版本,它反转了单个单词:

#include <stdio.h>

int main(void) {
    int num_tc, tc, len, left, right;
    char buf[31];

    if (scanf("%d\n", &num_tc) != 1)
        return 1;

    for (tc = 0; tc < num_tc; tc++) {
        if (scanf("%30s", buf) != 1)
            break;

        /* Compute the string length */
        for (len = 0; buf[len] != '[=11=]'; len++)
            continue;

        /* Reverse string in buf */
        for (left = 0, right = len - 1; left < right; left++, right--) {
            buf[left] ^= buf[right];
            buf[right] ^= buf[left];
            buf[left] ^= buf[right];           
        }
        puts(buf);
    }
    return 0;
}