代码之家  ›  专栏  ›  技术社区  ›  built1n

NCurses从stdin读取到std::string,C++

  •  -1
  • built1n  · 技术社区  · 12 年前

    我正在编写一个Linux应用程序,其中我必须使用ncurses从stdin读取密码。我可以毫无问题地读取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?
    }
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   andre    12 年前

    我不太清楚 sscanw 但是如果格式化工作类似 sscanf 我建议你限制输入的大小。

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

    安全性问题涉及缓冲区溢出(用户在缓冲区结束后写入程序空间)。要解决这个问题,只需限制字符数( %20s )你读取缓冲区的大小。