1
程序目标:获取要输入的字符串数,读取字符串,反转字符串并打印字符串。下一个字符串进行使用fgets读取字符串,无法获得第二个字符串的输出
#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
请让我知道为什么第二个字符串不采取串逆转。
- 如果我删除串反向逻辑,我可以看到两个字符串输出
@ gopi_2363:你可以标记这个答案通过点击答案得分下方的灰色勾选所接受? – chqrlie
当然。 1)S [strcspn(S,“\ n”)] ='\ 0';我不确定它会帮助这个计划。 2)我们可以用scanf编写相同的程序(我试过用[link](http://stackoverflow.com/questions/6282198/reading-string-from-input-with-space-character))3)有没有更好的方式来把这个scanf(“%d \ n”,&num_tc); –
你应该改变行内容,预先设置一个换行符,并用'puts()'附加另一个换行符看起来不合适。剥离换行似乎是合适的语义。所提出的方法适用于所有情况。你可以想象其他方法,比如在循环中测试''0'和''\ n',并在S [str_len]处强制'\ 0'。 – chqrlie