您的位置:首页 > 其它

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

2012-09-22 01:06 357 查看
// 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string 存储 c
相关文章推荐