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