[英]How do I populate an array with char values from the user in c?
I am new at C and coding in general, so please bear with me. 我是C的新手和编码,所以请耐心等待。
I am trying to create a "Keyboard testing" program where a user must populate an array by entering 1-character values in each element. 我正在尝试创建一个“键盘测试”程序,用户必须通过在每个元素中输入1个字符的值来填充数组。 The contents of the array will then be sorted and a
printf
will show which keys were pressed most (according to how many of each character was used). 然后将对数组的内容进行排序,
printf
将显示最多按下哪些键(根据使用的每个字符的数量)。 I've researched for two days to no avail (Most solutions are for C++, not C). 我研究了两天无济于事(大多数解决方案都是针对C ++而不是C)。 I am working in Visual Studios.
我在Visual Studios工作。 Here is what I have so far:
这是我到目前为止:
#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);
}
The output of this program seems to be the first character I typed in, so a part of it is working, though it only shows what is in keys[0]. 这个程序的输出似乎是我输入的第一个字符,因此它的一部分正在工作,尽管它只显示了键[0]中的内容。
How do I get it to store everything typed? 如何存储所有键入的内容?
How do I get printf to output the complete array? 如何让printf输出完整的数组?
How would I then go about passing the array to the function that will sort the contents in the elements? 那么我如何将数组传递给将对元素中的内容进行排序的函数呢?
(As far as arguments go in both main and the function declaration). (就主要和函数声明中的参数而言)。
You should use fgets()
to get a whole line. 你应该使用
fgets()
来获得整行。 Or if you must use scanf()
, note that %s
means a string instead of %c
which means one character. 或者如果必须使用
scanf()
,请注意%s
表示字符串而不是%c
表示一个字符。
#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;
}
I have included answers to your questions and you should be able to run with what is provided see below for details: 我已经包含了您的问题的答案,您应该可以使用提供的内容来查看详细信息:
How do I get it to store everything typed? 如何存储所有键入的内容?
char buffer[MAX_ELEMENTS];
char buffer[MAX_ELEMENTS];
. memset(buffer, 0, sizeof(char) * MAX_ELEMENTS);
memset(buffer, 0, sizeof(char) * MAX_ELEMENTS);
. Lastly, you need to read the user data into this buffer using the string formatter and scanf. 最后,您需要使用字符串formatter和scanf将用户数据读入此缓冲区。
scanf("%s", buffer);
. 。
How do I get printf to output the complete array? 如何让printf输出完整的数组?
All you need to do is use printf with the string formatter and your buffer as follows: 您需要做的就是将printf与字符串格式化程序和缓冲区一起使用,如下所示:
printf("Your sorted data is: %s\\n", buffer);
How would I then go about passing the array to the function that will sort the contents in the elements? 那么我如何将数组传递给将对元素中的内容进行排序的函数呢?
Create a sort function with a char
pointer in the parameter list: 使用参数列表中的
char
指针创建排序函数:
void sortData(char* data);
Next, pass the data buffer to the sort function as follows: 接下来,将数据缓冲区传递给sort函数,如下所示:
sortData(buffer);
All you need now is to implement the counting for multiple instances of the same character! 你现在需要的只是为同一个角色的多个实例实现计数!
Happy Programming!! 快乐编程!!
I am very glad I could help! 我很高兴能帮忙! I have updated my post with counting the number of times a character has been pressed.
我已经更新了我的帖子,计算了一个角色被按下的次数。 I also provide answers to your followup questions which I paraphrased to make it a little more clear.
我还提供了你的后续问题的答案,我将其解释为更加清晰。
What is the best way to count key presses? 计算按键的最佳方法是什么?
There are many ways this can be done but the most intuitive way to me is you need some kind of lookup table that can provide you an index. 有很多方法可以做到,但对我来说最直观的方法是你需要某种可以为你提供索引的查找表。
char charLookupTable[] = "abcdefghijklmnopqrstuvwxyz";
Keep in mind this table is only for lowercase characters if you wanted numbers or uppercase you could add them to the beginning and end respectively. 请记住,此表仅适用于小写字符,如果您想要数字或大写,则可以分别将它们添加到开头和结尾。 Now, create a function that will give you an index into this character string.
现在,创建一个函数,为您提供此字符串的索引。
int getIndex(char data);
Lastly, just create another table of integers to keep track of counts. 最后,只需创建另一个整数表来跟踪计数。
int countPressArray[sizeof(charLookupTable) - 1];
Just use the index to increment the correct count value (ie index:0 = 'a', index:1 ='b', . . ., index:25 = 'z', etc...). 只需使用索引来增加正确的计数值(即索引:0 ='a',索引:1 ='b',...,索引:25 ='z'等等...)。
countPressArray[countPressIndex]++;
Should I make a separate function for this? 我应该为此单独制作一个功能吗?
Yes, anytime you write code that is performing a specific task it is best to wrap it in a function. 是的,无论何时编写执行特定任务的代码,最好将其包装在函数中。 This allows the code to be more readable and easier to debug.
这使代码更易读,更容易调试。
How do I print each element in the array with no repeats? 如何在没有重复的情况下打印数组中的每个元素?
I didn't provide this in my code example above but it is easy enough to implement. 我没有在上面的代码示例中提供这个,但它很容易实现。 Now that we know how many times each key was pressed it is just a matter of checking to make sure it is not greater than 1 before you print.
现在我们知道按下每个键的次数,只需要检查以确保在打印之前它不大于1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.