【问题标题】:Sorting user input in lexicographical returning memory characters?以字典顺序返回内存字符对用户输入进行排序?
【发布时间】:2016-11-23 22:10:41
【问题描述】:

我正在尝试按字母顺序对最多 10,000 个单词和最大长度 25 个单词的用户输入进行排序。我正在使用“停止”来过早地结束用户输入,这让我遇到了一些问题。当我尝试输入 hello stop 时,当前程序的输出结果如下

 ▒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;

}

【问题讨论】:

  • 您没有将输入字符串保存到str的数组中。
  • 此外,abcwhile 循环第一次运行时未初始化。在发布问题之前打开编译器警告并修复所有警告。并学会使用调试器。如果您使用过调试器,问题应该会很清楚。
  • @WhozCraig 这种讽刺真的有必要吗?此外,您的句子中的“基准”也不正确。它应该是复数形式的“数据”。

标签: c string memory alphabetical lexicographic


【解决方案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

【讨论】:

  • 感谢您翻阅我的烂摊子!我很感激,会解决所有问题!
猜你喜欢
  • 1970-01-01
  • 2023-01-21
  • 1970-01-01
  • 2021-09-18
  • 2019-12-29
  • 2016-06-14
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多