实验目的:
在代码实践中熟悉队列这一重要数据结构,提高项目规划能力,提高写代码熟练度,了解掌握getch()函数。
预期效果:
输入非回车或退格字符后,显示"等待输入中...",并将输入字符缓存
输入退格删除上一次输入的字符
输入回车打印缓冲区字符与缓冲区字符个数
实验思路:
在缓冲循环中使用getch()读入字符,读入回车则结束缓冲循环,读入退格则执行退格函数,读入其他字符则将其加入缓冲队列。
实验代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/* 队列实现 */
#define MAXSIZE 100
#define ElementType char
struct QNode{
ElementType Data[MAXSIZE];
int Front,Rear;
int Size;
};
typedef struct QNode *Queue;
Queue createQueue(int Size){
if(Size<=MAXSIZE && Size>0){
Queue pQ;
pQ = (Queue)malloc(sizeof(struct QNode));
pQ->Front = 0;
pQ->Rear = 0;
pQ->Size = Size;
return pQ;
}
else{
puts("Error! Invalid size input when creating a new queue.");
return NULL;
}
}
int isFull(Queue Q){
return (Q->Front == (Q->Rear+1)%Q->Size);
}
int isEmpty(Queue Q){
return (Q->Front == Q->Rear);
}
void Enqueue(Queue Q, ElementType X){
if(!isFull(Q)){
Q->Rear = (Q->Rear+1)%Q->Size;
Q->Data[Q->Rear] = X;
}
else{puts("Error! The queue is full now.");}
}
ElementType Dequeue(Queue Q){
if(!isEmpty(Q)){
Q->Front = (Q->Front+1)%Q->Size;
return Q->Data[Q->Front];
}
else{puts("Error! The queue is empty now."); return 0;}
}
/* 队列实现 完 */
/* 主程序 */
// 退格实现
int DeleteLast(Queue Q) {
if(!isEmpty(Q)) {
Q->Rear = Q->Rear-1;
return 1;
}
else{puts("Error! The queue is empty now."); return 0;}
}
int main() {
// 创建缓冲队列
Queue bufferedQueue = createQueue(50);
// 临时变量初始化
char currentChar;
int waiting = 1;
int charCount = 0;
// 缓冲循环
while (waiting) {
puts("等待输入中...");
currentChar = getch();
// 读入回车则结束缓冲循环
if (currentChar==13) {
waiting = 0;
}
// 读入退格执行退格函数
else if (currentChar==8) {
if (DeleteLast(bufferedQueue)) {
charCount--;
}
}
// 读入其他字符,将其入队
else {
charCount++;
Enqueue(bufferedQueue,currentChar);
}
}
// 输出缓冲区
printf("缓冲区:");
while (!isEmpty(bufferedQueue)) {
printf("%c",Dequeue(bufferedQueue));
}
printf("\n共%d个字符(包含空格)\n",charCount);
getchar();
return 0;
}