【C++】C++行操作,退格,退行,空格输出。

//话不多说,代码先行。

#pragma once
#include <stdlib.h>
#include<iostream>
using namespace std;

#define STACK_INIT_SIZE 10
#define OVERFLOW - 2
#define OK 1
#define ERROR 0
typedef char SElemType;

//栈结构体
typedef struct
{
	SElemType* base;//栈底
	SElemType* top;//栈顶
	int stacksize;
}SqStack;


int InitStack(SqStack* S) //初始化栈
{
	S->base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
	if (!S->base)
	{
		exit(OVERFLOW);//OVERFLOW定义为-2
	}
	S->top = S->base;
	S->stacksize = STACK_INIT_SIZE;
	return OK;
}

int Push(SqStack* S, SElemType e)  //入栈
{
	*S->top++ = e;//先赋值在指针自加
	return OK;
}

int Pop(SqStack* S, SElemType* e)//删除栈中的元素
{
	if (S->top == S->base) return ERROR;//ERROR定义为0
	*e = *--S->top;
	return OK;
}

int ClearStack(SqStack* S)//清空栈中的元素
{
	S->top = S->base;
	return OK;
}

int DestoryStack(SqStack* S)//销毁栈
{
	S->top = S->base;
	free(S->base);
	S->top = NULL;
	S->base = NULL;
	return OK;
}

void LineEdit(SqStack* S)//行编辑程序
{
	SElemType* p, ch, c;
	char t = '1';
	int i = 1;
	InitStack(S);
	cout << "输入第" << i << "行:";
	ch = getchar();
	while (1)
	{
		while (ch != EOF) //EOF定义为-1
		{
			switch (ch)
			{
			case '#':Pop(S, &c); break;
			case '@':ClearStack(S); break;
			default:Push(S, ch); break;//传入字符
			}
			t = ch;
			ch = getchar();
			t = ch;
			if (ch != EOF && ch == '\n')
			{
				break;
			}
		}

		cout << "输出第" << i << "行:";
		p = S->base;
		while (p != S->top)
		{
			cout << *p;
			++p;
		}
		cout << endl << endl;
		ClearStack(S);
		i++;
		if (t == '\n')
		{
			cout << "输入第" << i << "行:";
			ch = getchar();
			if (ch == '\n')
			{
				cout << "您输入为空,已结束输入" << endl;
				break;
			}
		}
	}
}

int main()//005
{
	SqStack sq;
	cout << "**************        操作规则          **************" << endl;
	cout << "**************  1.输入'#'号为退格操作   **************" << endl;
	cout << "**************  2.输入'@'号为退行操作   **************" << endl;
	cout << "**************  3.输入'@'号即为空格行   **************" << endl;
	cout << "**************  4.输入回车即打印所在行  **************" << endl;
	cout << "**************  5.连续输入两次空则退出  **************" << endl;
	LineEdit(&sq);//进行括行编辑
	DestoryStack(&sq);//将栈销毁
	return 0;
}

//运行结果:

【C++】C++行操作,退格,退行,空格输出。

小小代码奉上,希望有所帮助。 

上一篇:简单易懂的MySql好操作且容易上手


下一篇:第七章 ⼀致性和可⽤性的权衡结果 BASE理论