【问题标题】:NCurses read from stdin to std::string, C++NCurses 从 stdin 读取到 std::string,C++
【发布时间】:2013-04-02 15:16:13
【问题描述】:

我正在编写一个 Linux 应用程序,其中我必须使用 ncurses 从标准输入读取密码。我可以毫无问题地读入 C 风格的字符串,但是,这会带来安全风险,所以我必须找到一种方法来读入 STL 字符串(std::string)。 这是我的代码的相关部分:

initscr();
noecho();
string key;
... // Get the key from the user
string enter=key+"A"; // So the entered key is not the user-set one
while(enter!=key)
{
    const char* msg="Key to unlock terminal? ";
    move(y/2, (x-strlen(msg))/2);
    erase();
    printw(msg);
    sscanw("%s", enter); // How do I read into an STL string?
}

【问题讨论】:

  • 我不知道有什么办法可以直接做到这一点。我认为您必须编写一个循环来一次读取一个字符并将每个字符附加到 std::string。
  • ncurses 似乎根本不支持 std::string,即使在他们的 C++ API 中也是如此。我可以在源代码中找到对“字符串”的唯一引用包括 C string.h 标头。
  • 将密码读入普通 C 字符串会带来安全风险吗?
  • 应该是锁屏的,像UNIX全屏终端一样,只能通过输入密码来关闭,而不是因为输入太多字符导致的缓冲区溢出或段错误
  • @john,现在我想起来了,我可以使用getch()...

标签: c++ string stl ncurses stdstring


【解决方案1】:

我对@9​​87654321@ 不太清楚,但如果格式化工作类似于sscanf,我建议您限制输入的大小。

char[21] enter;
sscanw("%20s", enter);
enter[20] = 0;

安全问题涉及缓冲区溢出(用户在缓冲区末尾之外写入程序空间)。要解决这个问题,只需限制您读入缓冲区大小的字符数 (%20s)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2015-09-24
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多