2016-11-23 54 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