程序目标:获取要输入的字符串个数,读取字符串,反转字符串并打印字符串。继续下一个字符串
#include <stdio.h> int main() { int num_tc, index_tc, char_idx, str_len = 0; char S[31]; scanf("%d\n", &num_tc); for (index_tc = 1; index_tc <= num_tc; index_tc++) { fgets(S, sizeof(S), stdin); /* To compute the string length */ for (char_idx = 0; S[char_idx] != NULL; char_idx++) str_len++; /* Reverse string S */ for (char_idx = 0; char_idx < str_len / 2; char_idx++) { S[char_idx] ^= S[str_len - char_idx - 1]; S[str_len - char_idx - 1] ^= S[char_idx]; S[char_idx] ^= S[str_len - char_idx - 1]; } puts(S); } return 0; }
程序的输入
2<\n> ab<\n> aba<\n>
输出
ba
请告诉我为什么不将第二个字符串用于字符串反转。
- 如果我删除字符串反转逻辑,我可以看到两个字符串输出
最佳答案
您不要在循环体中将 str_len
重置为 0
。第二个字符串的长度不正确,因此第二个字符串没有正确反转。将循环更改为:
for (str_len = 0; S[str_len] != '\0'; str_len++)
continue;
请注意,在反转字符串之前,您应该去除尾随的 '\n'
。您可以在计算 str_len
之前使用 S[strcspn(S, "\n")] = '\0';
执行此操作。
这是一个使用 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] != '\0'; 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;
}
关于c - 使用 fgets 读取字符串,无法获取第二个字符串的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38415368/