注册 登录
编程论坛 C++教室

字符串类型末尾减一个字符怎么弄?

ehszt 发布于 2016-08-31 07:47, 1683 次点击
比如定义一个字符串类型为string a;
a="today is sunday";
想把a变为today is sunda,有没有什么快捷的方法?
3 回复
#2
rjsp2016-08-31 08:25
C++11 中可直接使用 std::basic_string::pop_back() 函数
C++标准是这么描述pop_back()的
Removes the last character from the string.

Equivalent to erase(size()-1, 1), except the behavior is undefined if the string is empty.

那么,在C++11之前,当然就是 erase(size()-1, 1) 了。同样,要注意string是否为空。
#3
ehszt2016-08-31 09:08
回复 2楼 rjsp
不知道咋用,我只是想做个密码输入类
class Key
{
    public:
        int cmp()
        {
            
            cout<<setw(30)<<"请输入密码:"<<endl;
            while((ch=_getch())!='\r')
            {
               
                if(ch=='\b')
                {
                    
                    cout<<"\b \b";
                    password.pop_back();
                    continue;
                }
               
                password.push_back(ch);
                cout<<"*";
            }
            if(password==pass)
            return 1;
            else
            return 0;

            
        }
    private:
        char ch;
        vector<char> password;
        vector<char> pass="eb36520";
};
#4
rjsp2016-08-31 10:29
回复 3楼 ehszt
根据你的代码意图,我瞎写的,你参考一下吧

程序代码:
#include <conio.h> // vc only 非标准的东西

#include <cstdio>
#include <string>

std::string GetPassord( void )
{
    // 清除之前遗留的所有输入
    for( ; _kbhit(); ) _getch();

    std::string pwd;
    for( int ch; ch=_getch(), ch!='\r'; )
    {
        if( ch==0 || ch==0xE0 ) // 功能键
            _getch();
        else if( ch == 0x1B ) // ESC键
        {
            for( size_t i=0; i!=pwd.size(); ++i )
                printf( "\b \b" );
            pwd.clear();
        }
        else if( ch == '\b' ) // 退格键
        {
            if( !pwd.empty() )
            {
                printf( "\b \b" );
                pwd.erase( pwd.size()-1 );
            }
        }
        else if( ch>=0x20 && ch<0x7F ) // 可显字符
        {
            putchar( '*' );
            pwd += ch;
        }
    }

    // 清除之前遗留的所有输入
    for( ; _kbhit(); ) _getch();
    putchar( '\n' );

    return pwd;
}

int main( void )
{
    printf( "%s", "Enter password: " );
    std::string pwd = GetPassord();

    // puts( pwd.c_str() );

    if( pwd != "eb36520" )
    {
        puts( "Password error\n" );
        return 1;
    }
    puts( "\nDo Well\n" );

    return 0;
}

1