在我的循环结束时,我有:
cout<<"nn any key to continue or Ctrl+Z to exit.";
它允许用户继续输入数据,或通过按 CtrlZ 退出。我想在用户决定继续输入数据时隐藏按下的键。
我不希望当用户按任何键保持循环时出现按下的键。我该怎么做?我正在使用开发C++。我的函数的代码如下。
void student::read()
{
char response; ofstream OS ("student.dat", ios::app);
do
{
cout<<"Name: ";
cin>>name;
cout<<"Age: ";
cin>>age;
cout<<"GPA: ";
cin>>GPA;
//calling writefile to write into the file student.dat
student::writefile();
cout<<"nn any key to continue or Ctrl+Z to exit."<<endl<<endl;
cin>>response;
cin.ignore();
}
while(cin); //Ctrl+Z to exit
}
方法可以解决这个问题
但这取决于您使用的操作系统
http://opengroup.org/onlinepubs/007908799/xcurses/curses.h.htmlhttp://en.wikipedia.org/wiki/Conio.h
选项 1:使用conio.h的Windows。
getch()
或者对于 *nix 使用 curses.h
getch()
选项 2:在 Windows 中,您可以使用 SetConsoleMode() 关闭任何标准输入函数的回显。法典:
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main()
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
string s;
getline(cin, s);
cout << s << endl;
return 0;
}//main
或 *尼克斯·西尔
#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>
using namespace std;
int main()
{
termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
termios newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
string s;
getline(cin, s);
cout << s << endl;
return 0;
}//main