【问题标题】:How do I populate an array with char values from the user in c?如何在 c 中使用来自用户的 char 值填充数组?
【发布时间】:2016-12-04 01:35:59
【问题描述】:

我是 C 和一般编码方面的新手,所以请多多包涵。

我正在尝试创建一个“键盘测试”程序,其中用户必须通过在每个元素中输入 1 个字符的值来填充数组。然后将对数组的内容进行排序,printf 将显示哪些键被按下的次数最多(根据每个字符的使用次数)。我研究了两天无济于事(大多数解决方案都是针对 C++,而不是 C)。我在 Visual Studios 工作。这是我目前所拥有的:

#define _CRT_SECURE_NO_WARNINGS
#define PAUSE system("pause")
#define CLS system ("cls")
#define FLUSH flush()
#define MAXELEMENTS 25 
#include <stdio.h>
#include <stdlib.h>

// prototyped functions
int pressKeys(char keys);

main() {
  char keys[MAXELEMENTS];
  int x;

  pressKeys(&keys[MAXELEMENTS]);
  PAUSE;
}

// functions

int pressKeys(char keys) {
  printf("Enter characters: \n");
  scanf("%c", &keys); FLUSH;

  printf("You typed: %c\n", keys);

  return(0);
}

这个程序的输出似乎是我输入的第一个字符,所以它的一部分正在工作,虽然它只显示了 keys[0] 中的内容。

如何让它存储输入的所有内容?
如何让 printf 输出完整的数组?
然后我将如何将数组传递给将对元素中的内容进行排序的函数?

(就主要和函数声明中的参数而言)。

【问题讨论】:

  • 出于好奇,您是否反对为此使用 C++?您是在学习特定的 C 编程课程,还是只是想在学习续集之前先学习原版?
  • BTW &amp;keys[MAXELEMENTS] 是最后一个元素的地址。 (而且它不使用:-)
  • 用户是在输入结束时在其他键之间输入回车键还是根本不输入?

标签: c arrays char scanf


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int getIndex(char data);
void sortData(char* data);
void flushConsole(void);

#define MAX_ELEMENTS 25

// This table is used for looking up an index
char charLookupTable[] = "abcdefghijklmnopqrstuvwxyz";    

int main(void)
{
  // Create a buffer to hold the user input & clear it out before using
  char buffer[MAX_ELEMENTS]; 
  memset(buffer, 0, sizeof(char) * MAX_ELEMENTS);

  // Create a table to hold the number of times each key has been pressed
  // this table will be 1 less than the size of character lookup table since
  // it doesn't have a NULL at the end
  int countPressArray[sizeof(charLookupTable) - 1];
  memset(countPressArray, 0, sizeof(countPressArray));

  // Get the user data and read it into a buffer
  printf("Enter characters: ");
  scanf("%s", buffer);

  // Sort the user input data
  sortData(buffer);

  // Now that the data is sorted let's see how many times a specific character was used
  int index = 0;
  while(buffer[index] != NULL)
  {
    // Get the index of the counter to increment
    int countPressIndex = getIndex(buffer[index]);

    // Now increment the count in the table for each key press
    countPressArray[countPressIndex]++;

    // Check the next character
    index++;
  }

  // Clear the console buffer
  flushConsole();

  // Print the sorted data
  printf("Your sorted data is: %s\n", buffer);

  // Hold the console window open
  printf("\nPress any key to continue...");
  getchar();  

  // Exit the program
  return 0;
}


// This function will sort the data in the array using 
// a simple bubble sort algorithm.
void sortData(char* data)
{
  for (int i = 0; ; i++)
  { 
    if (data[i] == NULL)
    {
      // Everything is now in order
      break;
    }

    for (int j = i + 1; ; j++)
    {  
      if (data[j] == NULL)
      {
        // All values have been compared look at the next value
        break;
      }

      if (data[i] > data[j])
      {
        // The values need to be swapped use a temporary value as a third hand 
        char temp = data[i];
        data[i] = data[j];
        data[j] = temp;
      }
    }
  }
}

// This function flushes the console
void flushConsole(void)
{
  while (getchar() != '\n');
}

// This function will return the index of the character that was pressed
int getIndex(char data)
{
  for (int i = 0; i < sizeof(charLookupTable) / sizeof(char); i++)
  {
    if (data == charLookupTable[i])
    {
      // We have found a match return the index of the character
      return i;
    }
  }

  // Couldn't find this character in the table return an error
  return 0xFF;
}

我已包含对您问题的答案,您应该能够使用所提供的内容运行,详情请参见下文:

  • 如何让它存储输入的所有内容?

    1. 首先,您需要创建一个字符缓冲区char buffer[MAX_ELEMENTS];

    2. 接下来,您需要清除此缓冲区,因为它位于堆栈上并且已使用垃圾进行初始化。您可以使用 memset(buffer, 0, sizeof(char) * MAX_ELEMENTS); 来执行此操作。

    3. 最后,您需要使用字符串格式化程序和 scanf 将用户数据读入此缓冲区。

      scanf("%s", buffer);.

  • 如何让 printf 输出完整的数组?

    您需要做的就是将 printf 与字符串格式化程序和缓冲区一起使用,如下所示:

    printf("Your sorted data is: %s\n", buffer);

  • 然后我将如何将数组传递给将对元素中的内容进行排序的函数?

    1. 用参数列表中的char指针创建一个排序函数:

      void sortData(char* data);

    2. 接下来,将数据缓冲区传递给排序函数,如下所示:

      sortData(buffer);

您现在只需要实现对同一字符的多个实例的计数!

编程愉快!!


我很高兴能帮上忙!我更新了我的帖子,计算了一个字符被按下的次数。我还为您的后续问题提供了答案,我对其进行了转述以使其更加清晰。

  • 计算按键次数的最佳方法是什么?

    有很多方法可以做到这一点,但对我来说最直观的方法是您需要某种可以为您提供索引的查找表。

    char charLookupTable[] = "abcdefghijklmnopqrstuvwxyz";

    请记住,此表仅适用于小写字符,如果您需要数字或大写字母,您可以分别将它们添加到开头和结尾。现在,创建一个函数,为您提供该字符串的索引。

    int getIndex(char data);

    最后,只需创建另一个整数表来跟踪计数。

    int countPressArray[sizeof(charLookupTable) - 1];

    只需使用索引来增加正确的计数值(即 index:0 = 'a'、index:1 ='b'、...、index:25 = 'z' 等...)。

    countPressArray[countPressIndex]++;

  • 我应该为此创建一个单独的函数吗?

    是的,每当您编写执行特定任务的代码时,最好将其包装在一个函数中。这使代码更具可读性和更易于调试。

  • 如何打印数组中的每个元素而不重复?

    我没有在上面的代码示例中提供这个,但它很容易实现。现在我们知道每个键被按下了多少次,只需在打印之前检查以确保它不大于 1。

【讨论】:

  • 你帮了大忙,布兰登!我试图弄清楚如何从您的代码中计算迭代次数,但似乎无法弄清楚。我得到的最接近(我使用了一个 for 循环)是“NULL 发生的次数少于“#”次”,所以在尝试搜索数组时出现了问题。对我来说最简单的方法是什么?这次我需要找出如何打印数组中的每个元素,但不能重复。顺便说一句,我应该为此创建一个单独的函数吗?
  • 我很高兴能帮上忙!我已更新我的帖子以解决您的后续问题!最好的问候!
  • 再次感谢您的帮助,布兰登!如果可以的话,你能帮我更好地理解代码吗? (为什么要输入您输入的内容)例如,在这一行中: memset(buffer, 0, sizeof(char) * MAX_ELEMENTS); memset 是指为其角色预留的内存,对吧? 0 代表什么?还有,NULL的作用是什么?
  • memset 用于初始化一块内存(栈或堆)。它有 3 个参数 1.) 指向内存位置(即缓冲区)的指针。 2.) 用于初始化的值(即用 0 填充位置)。 3.) 从指针开始设置的字节数(即从缓冲区开始用 0 初始化 25 个字节)。由于在声明变量时可以将堆栈和堆初始化为任何内容,因此将其置于已定义状态(将其清除)非常重要。 NULL 正如它所说的,它什么都不是!这用于初始化和检查的指针。
【解决方案2】:

您应该使用fgets() 来获取整行。或者如果您必须使用scanf(),请注意%s 表示一个字符串,而不是%c 表示一个字符。

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多