首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >检测进入键C++

检测进入键C++
EN

Stack Overflow用户
提问于 2020-08-08 21:29:59
回答 1查看 106关注 0票数 1

我试图屏蔽用户输入并将其存储在一个变量中。但是,当我按enter键时,程序应该从循环中中断,enter键仍然注册为字符:

代码语言:javascript
代码运行次数:0
运行
复制
#inlcude <iostream>
#include <conio.h>

std::cout << "Password: ";

char c;

// Masks the password
while ((c = _getch()))
{
    if (c == '\n')
    {
        break;
    }

    passwd.push_back(c); // put it onto the back of the password
    _putch('*'); // output a '*' character
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-08 21:36:51

在许多系统(包括Windows)中,换行符‘'\n'’实际上表示两个字符的组合:一个回车(ASCII 13)加上一个行提要(ASCII 10)。

对于"Enter“键(也就是回车返回),请使用'\r'转义序列:

代码语言:javascript
代码运行次数:0
运行
复制
#include <iostream>
#include <string>
#include <conio.h>

int main()
{
    std::string passwd;
    std::cout << "Password: ";
    char c;
    // Masks the password
    while ((c = _getch())) {
        if (c == '\r') {
            break;
        }
        passwd.push_back(c); // put it onto the back of the password
        _putch('*'); // output a '*' character
    }
    std::cout << std::endl << passwd << std::endl;
    return 0;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63320402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档