2016-11-23 25 views
0

我正在嘗試按字母順序排列用戶輸入,最多10,000個單詞,最大長度爲25個單詞。我正在使用「停止」來提前終止用戶輸入,這會使我陷入一些問題。下面爲輸出當前程序的結果,當我嘗試輸入你好停止按字典返回記憶字符對用戶輸入進行排序?

▒l▒ 
0▒l▒ 
A{▒ 
e▒ 



▒& 
▒▒ 
▒▒ 
▒▒ 
▒▒ 
▒l▒ 
▒l▒ 
▒▒; 
▒Se▒ 
▒ 
▒ 
▒ 
▒ 





▒! 
Ќl▒ 
▒ 
▒ 
▒ 
▒.X 

▒ 

我假定這是與我的內存分配做,但我也不太清楚,但沒有找到對此一些答案。任何幫助,將不勝感激,下面是我的代碼

#include<stdio.h> 
#include <string.h> 

//for using tolower 
#include <ctype.h> 
int main() { 
    int i, k, j; 
    char abc[25]; 
    const char *stop = "stop"; 
    char *p; //using for lowercase 
    //using 2d array for max of 10,000 words, max size of words 25 
    char str[10000][25], temp[25]; 

    printf("Enter up to 10000 words, type stop to enter the current words:\n"); 
    while (strncmp(abc, "stop", 5) != 0) { 
     scanf("%s", abc); 
    } 
     //for (i = 0; i < 10000; ++i) 
      //scanf("%s[^\n]", str[i]); 

     for (i = 0; i < 10000; ++i) 
      for (k = i + 1; k < 10000; ++k) { 
       //comparing two strings using strcmp() function is used 
       //using strcpy() to copy string to a temp 
       if (strcmp(str[i], str[k]) > 0) { 
        strcpy(temp, str[i]); 
        strcpy(str[i], str[k]); 
        strcpy(str[k], temp); 
       } 
      } 

     //using pointer to converting to lowercase 
     //src: https://www.daniweb.com/programming/software-development/threads/57296/how-does-one-tolower-an-entire-string 
     for (p = str; *p != '\0'; p++) 
      *p = (char) tolower(*p); 

     //printing words in lexi order 
     printf("\nWords in lexicographical order: \n"); 
     for (i = 0; i < 10000; ++i) { 
      puts(str[i]); 
     } 
     printf("WARNING: Words longer than 25 in length were ignored. \n"); 

     return 0; 

} 
+2

不保存輸入將字符串轉換爲'str'數組。 – BLUEPIXY

+2

另外,'while'循環首次運行時,'abc'沒有初始化。在發佈問題之前,打開您的編譯器警告並修復所有這些警告。並學會使用調試器。如果您使用過調試器,問題應該清楚。 – kaylum

+0

@WhozCraig那諷刺真的有必要嗎?另外,'datum'在你的句子中不正確。它應該是複數的「數據」。 – DIMMSum

回答

1

的代碼有以下嚴重問題(請忽略小寫指針,在獲取輸出變成小寫還在工作!):

  • str字符串數組未初始化。它可能包含完整的垃圾,包括沒有空終止符的字符串。
  • 後聲明遍歷所有這些垃圾字符串,這可能(和不一般)沒有結束這麼好...
  • 你的「降低」循環,你不處理字符串數組,如果它是一個單個字符串。
  • 你在一個臨時變量中讀了很多字符串,但是你沒有對它們做任何事情。

爲了解決這個問題,您只需要通過有效的字符串,以保持在你的陣列中的項目數的跟蹤和迭代:

int n=0; 
while (scanf("%24s", abc)>0 && strncmp(abc, "stop", 5) != 0) { 
    strncpy (str[n++], abc, 25); 
} 

for (i = 0; i < n; ++i) 
    for (k = i + 1; k < n; ++k) { 
     ... 
    } 
    ... 
} 
for (i =0; i<n; i++) 
    for (p = str[i]; *p != '\0'; p++) 
     *p = (char) tolower(*p); 
... 
for (i = 0; i < n; ++i) { 
     puts(str[i]); 
} 
... 

這裏的online demo

+0

謝謝你過去我的混亂!我很感激,會解決所有的問題! – Nuggets10

相關問題