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

string 和 char 的问题,密码变“*”号

qq1274371820 发布于 2014-06-10 13:48, 515 次点击

          一个小小的密码变“*”号的程序,按“@”键结束输入,但是不管怎么输入,结果都显示为 “ b:@   c:@”,我想要的是  
           
           b 和 c 都为输入的值,要怎么改?

#include "stdafx.h"
#include"iostream"
#include"string"
#include"string"
#include"conio.h"
using namespace std;int main()
{
    string c;
    do
    {
        c=getch();
        if(c=="@")
            break;
        cout<<"*";
    }while(c!="@");
    char b[20];
    strcpy(b,c.c_str());
    cout<<"b:"<<b<<endl;
    cout<<"c:"<<c.c_str()<<endl;
    return 0;
}
4 回复
#2
rjsp2014-06-10 14:27
程序代码:
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

int main()
{
    std::string password;

    while( 1 )
    {
        char c = _getch();

        if( c==0 || c==(char)0xE0 ) // function key or arrow key
        {
            _getch();
            continue;
        }

        if( c == 0x03 ) // ctrl+c
            return 1;

        if( c == '\r' ) // carriage return
        {
            cout << endl;
            break;
        }

        cout << '*' << flush;
        password += c;
    }

    cout << password << endl;
    return 0;
}
#3
qq12743718202014-06-10 15:17


             感觉好难懂。。。如果要再来一段一样的代码,然后比较前后输入值的大小,怎么做?
#4
rjsp2014-06-10 15:32
程序代码:
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

std::string getpassword()
{
    std::string password;

    while( 1 )
    {
        char c = _getch();

        if( c==0 || c==(char)0xE0 ) // function key or arrow key
        {
            _getch();
            continue;
        }

        if( c == 0x03 ) // ctrl+c
            exit( 1 );

        if( c == '\r' ) // carriage return
        {
            cout << endl;
            break;
        }

        cout << '*' << flush;
        password += c;
    }

    return password;
}

int main()
{
    cout << "Enter password 1: ";
    std::string pwd1 = getpassword();
    cout << "Enter password 2: ";
    std::string pwd2 = getpassword();

    if( pwd1 > pwd2 )
        cout << "password1 > password2" << endl;
    else if( pwd1 < pwd2 )
        cout << "password1 < password2" << endl;
    else
        cout << "password1 == password2" << endl;

    return 0;
}
#5
qq12743718202014-06-10 16:57

               大神啊
1