使用 fgets 读取字符串,无法获取第二个字符串的输出
Reading a string using fgets, couldn't get output of second string
Objective of Program : 获取要输入的字符串个数,读取字符串,反转字符串,打印字符串。继续下一个字符串
#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] != '[=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;
}
Objective of Program : 获取要输入的字符串个数,读取字符串,反转字符串,打印字符串。继续下一个字符串
#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] != '[=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;
}