2016-07-16 26 views
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 
    
  • 請讓我知道爲什麼第二個字符串不採取串逆轉。

  • 如果我刪除串反向邏輯,我可以看到兩個字符串輸出

回答

2

你不復位str_len0在循環體。第二個字符串的長度不正確,因此第二個字符串沒有正確反轉。更改環路:

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; 
} 
+0

@ gopi_2363:你可以標記這個答案通過點擊答案得分下方的灰色勾選所接受? – chqrlie

+0

當然。 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); –

+0

你應該改變行內容,預先設置一個換行符,並用'puts()'附加另一個換行符看起來不合適。剝離換行似乎是合適的語義。所提出的方法適用於所有情況。你可以想象其他方法,比如在循環中測試''0'和''\ n',並在S [str_len]處強制'\ 0'。 – chqrlie

相關問題