Consol应用中的字符限制控制器 [英] Character Limit Controller in Consol Application

查看:109
本文介绍了Consol应用中的字符限制控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写过的这个方法有问题,如果用户不完整字符串的所有字符,空格无处不在,我该怎么办?



< pre lang =c ++> string CharacterLimitController( int limit)
{
int count = 0 ;
char c;
string A;
A.resize(限制,' ');
执行
{
c = getch();
if (c == 8
{
if (count> 0)
{
cout<< \b \b;
count - = 1 ;
}
继续;
}
如果(count == limit)
{
count - = 1 ;
cout<< \ b;
}
如果(c == 13
断裂;
A [count] = c;
cout<< C;
count ++;
}
while (count!= limit + 1);



return A;
}

解决方案

在用户完成输入时使用空字符。 null字符为零


如果你不想用任何额外的字符填充输出字符串,请删除该行

 A.resize (limit,' '); 

此方法指示填充字符串空白空间中的空白空间。有关string.resize的更多信息,请访问此处 [ ^ ]


如果要删除两端的空格,一旦用户离开循环,修剪字符串可能更简单。



或者,您可能不会在开头填充空格但添加一个字符在适当的时候到字符串的末尾,当用户按退格键时删除最后一个字符。



鉴于您已经保留了计数,以下可能是您想要的:



  return  A.substr( 0 ,count); 


This method i already wrote, have a problem, Spaces are everywhere if user don''t full all characters of strings,what should i do ?

string CharacterLimitController(int limit)
{
	int count =0;
	char c;
	string A;
    A.resize(limit,' ');
	do
	{
	    c=getch();
		if(c==8)
		{
			if(count >0)
			{
			    cout <<"\b \b"; 
		   	    count -=1;
			}
			continue;
		}
		if(count==limit)
		{
			count -=1;
		    cout<<"\b";
		}
		if(c==13)
			break;
	    A[count]=c;
		cout << c;
	    count ++;
	}
	while(count!=limit+1);
       
    

	return A;
}

解决方案

use a null character when user finish inputting. null character is zero


If you dont want to fill your output string with any additional char remove the line

A.resize(limit,' ');

this method instructs to fill the empty spaces in the string empty space. see more about string.resizehere[^]


If you want to remove spaces at both ends, it is probably simpler to trim the string once the user get out of the loop.

Alternatively, you might not fill the string with space at the beginning but add one character to the end of the string as appropriate and when the user press backspace remove last character.

Given that you already keep the count, the following might be what you want:

return A.substr(0, count);


这篇关于Consol应用中的字符限制控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆