实现命令行输入及键盘消息处理

22 篇文章 0 订阅
11 篇文章 0 订阅
// StringTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


// string::empty
// string::clear
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;

void ShowHelp()
{
	printf("==========Help Infomation============\n");
	printf(">");
}



int main (char * argv[],int argc)
{
  string str = "";
  char ch = 0;
  
  cout << "Please type some lines of text. Enter a period to finish\n>";
  do 
  {
    ch=getch();
	str += ch;
	
	printf("%c",ch);

	//处理按键
	switch(ch)
	{
	case 8://处理 Backspace 键
		//cout << endl << "size=" << str.size() << endl;
		if (str.size() == 1) //str中不存储退格键,置空
		{
			str = "";
		}
		
		if (str.size() >= 2)//空格+将要删除的字符,所以至少要有两个字符
		{
			string strTemp = "";
			int iCnt=0;
			strTemp = str.erase(str.size()-2);//删除倒数第二个字符,倒数第一个字符是'\0',不能删除
			
			printf("\r>");
			while(1)
			{
				printf(" ");
				if (iCnt++ > str.size())
				{
					break;
				}
			}
			
			printf("\r>%s",strTemp.c_str());
		}
		
		continue;
		break;
	case 3://处理ctrl+c键
		printf("\n<Ctrl>+<c>\n");
		exit(-1);
	case 4://处理ctrl+d键
		printf("\n<Ctrl>+<d>\n");
		exit(-1);
		break;
		
	default:
		//printf("%d",ch);
		break;
	}

	
	//printf("\n%d",ch);

	if ( ('?' == ch) && (1 == str.size()) )
	{
		printf("\n");
		ShowHelp();
		str = "";
		continue;
	}

	if (ch == 13)
    {
		string strTemp = str;
		//cout << endl << str << endl;
		//cout << "str.size()=" << str.size() << endl;
		cout << endl << str ;
		str = "";
		
		//只有空格一个字符,不处理
// 		if (1 == strTemp.size())
// 		{
// 			//cout << ">";
// 		}

		//除了空格还有一个字符
		if (2 == strTemp.size())
		{
			char cTemp = strTemp.at(0);
			switch(cTemp)
			{
				case 1:
					cout << "====1======" << endl;
					break;
				default:
					cout << "====" << cTemp << endl;
					break;
			}
			
		}

		//两个或两个以上字符处理
		if ( 3 <= strTemp.size())
		{
			cout << endl;
			//....
		}

		cout << ">";
		//str.clear();//string 没有clear()成员函数?
    }
	
  } while (1);
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值