I am trying to write a C++ program in which when user enter any character from keyboard and it should move to next line of code.
我正在尝试编写一个c++程序,当用户从键盘输入任何字符时,它应该移动到下一行代码。
Here is my code:
这是我的代码:
char c;
cin>>c;
cout<<"Something"<
but this is not working, because it only move to next line when I input some character and then press ENTER.
但这行不通,因为它只会移动到下一行当我输入某个字符然后按ENTER。
OR
或
If I use this
如果我用这个
cin.get() or cin.get(c)
it move to next line of instruction when I press Enter.
当我按回车键时,它移动到下一行。
But I wanted it to move to next line on any key pressed on the keyboard, how this can be done?
但是我想让它移动到键盘上任何按键上的下一行,这是怎么做到的呢?
50
If you're on Windows, you can use kbhit()
which is part of the Microsoft run-time library. If you're on Linux, you can implement kbhit
thus (source):
如果您在Windows上,可以使用kbhit(),它是Microsoft运行时库的一部分。如果您在Linux上,那么可以实现kbhit(源代码):
#include
#include
#include
#include
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
Update: The above function works on OS X (at least, on OS X 10.5.8 - Leopard, so I would expect it to work on more recent versions of OS X). This gist can be saved as kbhit.c
and compiled on both Linux and OS X with
更新:上面的函数在OS X上工作(至少在OS X 10.5.8 - Leopard上,所以我希望它能在最近版本的OS X上运行)。并在Linux和OS X上编译。
gcc -o kbhit kbhit.c
When run with
运行时
./kbhit
It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).
它提示您输入一个按键,当您点击一个键(不限于输入或可打印的键)时退出。
@Johnsyweb - please elaborate what you mean by "detailed canonical answer" and "all the concerns". Also, re "cross-platform": With this implementation of kbhit()
you can have the same functionality in a C++ program on Linux/Unix/OS X/Windows - which other platforms might you be referring to?
@Johnsyweb -请详细说明你所说的“详细规范答案”和“所有关注事项”。另外,re“跨平台”:在kbhit()的实现中,您可以在Linux/Unix/OS X/Windows上的c++程序中拥有相同的功能——您可能指的是其他平台?
Further update for @Johnsyweb: C++ applications do not live in a hermetically sealed C++ environment. A big reason for C++'s success is interoperability with C. All mainstream platforms are implemented with C interfaces (even if internal implementation is using C++) so your talk of "legacy" seems out of place. Plus, as we are talking about a single function, why do you need C++ for this ("C with classes")? As I pointed out, you can write in C++ and access this functionality easily, and your application's users are unlikely to care how you implemented it.
@Johnsyweb的进一步更新:c++应用程序不存在于密封的c++环境中。c++成功的一个重要原因是与C的互操作性。所有主流平台都是用C接口实现的(即使内部实现使用c++),所以您的“遗留”话题似乎已经过时了。另外,当我们讨论一个函数时,为什么需要c++来实现这个(“C和类”)?正如我指出的那样,您可以在c++中编写并轻松地访问该功能,您的应用程序的用户不太可能关心您是如何实现它的。
48
On Windows:
在Windows上:
system("pause");
and on Mac and Linux:
在Mac和Linux上:
system("read");
will output "Press any key to continue..." and obviously, wait for any key to be pressed. I hope thats what you meant
将输出“按任意键继续…”,显然,等待任何键被按下。我希望你是这个意思。
7
There is no completely portable solution.
没有完全可移植的解决方案。
Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.
问题19.1 .朗。c FAQ在一些深度上涵盖了这个问题,包括Windows、unix系统,甚至MS-DOS和vm的解决方案。
A quick and incomplete summary:
快速而不完整的摘要:
curses
library; call cbreak()
followed by getch()
(not to be confused with the Windows-specific getch()
function). Note that curses
generally takes control of the terminal, so this is likely to be overkill.ioctl()
to manipulate the terminal settings.tcgetattr()
and tcsetattr()
may be a better solution.system()
to invoke the stty
command.getch()
or getche()
.SMG$
) routines might do the trick.All these C solutions should work equally well in C++; I don't know of any C++-specific solution.
所有这些C解决方案应该在c++中同样有效;我不知道有什么c++特定的解决方案。
6
To achieve this functionality you could use ncurses library which was implemented both on Windows and Linux (and MacOS as far as I know).
为了实现这个功能,您可以使用ncurses库,它在Windows和Linux上都实现了(据我所知是MacOS)。
4
I looked into what you are trying to achieve, because I remember I wanted to do the same thing. Inspired by Vinay I wrote something that works for me and I sort of understand. But I am not an expert, so please be careful.
我研究了你想要达到的目标,因为我记得我也想做同样的事情。受Vinay的启发,我写了一些对我有用的东西,我也能理解。但我不是专家,所以请小心。
I don't know how Vinay knows you are using Mac OS X. But it should work kind of like this with most unix-like OS. Really helpful as resource is opengroup.org
我不知道Vinay如何知道你在使用Mac OS x,但它应该是类似于大多数unix操作系统的。真正有用的资源是opengroup.org。
Make sure to flush the buffer before using the function.
在使用该函数之前,请确保刷新缓冲区。
#include
#include //termios, TCSANOW, ECHO, ICANON
#include //STDIN_FILENO
void pressKey()
{
//the struct termios stores all kinds of flags which can manipulate the I/O Interface
//I have an old one to save the old settings and a new
static struct termios oldt, newt;
printf("Press key to continue....\n");
//tcgetattr gets the parameters of the current terminal
//STDIN_FILENO will tell tcgetattr that it should write the settings
// of stdin to oldt
tcgetattr( STDIN_FILENO, &oldt);
//now the settings will be copied
newt = oldt;
//two of the c_lflag will be turned off
//ECHO which is responsible for displaying the input of the user in the terminal
//ICANON is the essential one! Normally this takes care that one line at a time will be processed
//that means it will return if it sees a "\n" or an EOF or an EOL
newt.c_lflag &= ~(ICANON | ECHO );
//Those new settings will be set to STDIN
//TCSANOW tells tcsetattr to change attributes immediately.
tcsetattr( STDIN_FILENO, TCSANOW, &newt);
//now the char wil be requested
getchar();
//the old settings will be written back to STDIN
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}
int main(void)
{
pressKey();
printf("END\n");
return 0;
}
O_NONBLOCK seems also to be an important flag, but it didn't change anything for me.
O_NONBLOCK似乎也是一个重要的标志,但它并没有改变我的任何东西。
I appreciate if people with some deeper knowledge would comment on this and give some advice.
如果有更深入的知识的人对此发表评论并给出一些建议,我将不胜感激。
4
You could use the Microsoft-specific function _getch:
你可以使用microsoftspecific function _getch:
#include
#include
// ...
// ...
// ...
cout <<"Press any key to continue..." <
4
This is very simple . I made a program and it works perfect..Here is the program.
这很简单。我做了一个程序,它很完美。这是程序。
#include
#include
void check()
{
char chk; int j;
cout<<"\n\nPress any key to continue...";
chk=getch();
j=chk;
for(int i=1;i<=256;i++)
if(i==j) break;
clrscr();
}
void main()
{
clrscr();
check();
cout<<"\n\nSee, Its Working....Have a Good day";
getch();
}
3
This works on a Windows Platform: It Uses the Microprocessor registers directly and can be used to check key press or mousebutton
这在Windows平台上运行:它直接使用微处理器寄存器,可以用来检查按键或鼠标按钮。
#include
#include
#include
void main()
{
clrscr();
union REGS in,out;
in.h.ah=0x00;
printf("Press any key : ");
int86(0x16,&in,&out);
printf("Ascii : %d\n",out.h.al);
char ch = out.h.al;
printf("Charcter Pressed : %c",&ch);
printf("Scan code : %d",out.h.ah);
getch();
}
2
If you're using Visual Studio 2012 or older, use the "getch()" function, if you are using Visual Studio 2013 or newer, use "_getch()". You will have to use "#include
如果你使用的是Visual Studio 2012或更老的,使用“getch()”函数,如果你使用Visual Studio 2013或更新,使用“_getch()”。您必须使用“#include
#include "stdafx"
#include
#include
int main()
{
std::cout <<"Press any key to continue. . .\n"
_getch() //Or "getch()"
}
1
You can use the getchar routine.
可以使用getchar例程。
From the above link:
从上面的链接:
/* getchar example : typewriter */
#include
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
0
Also you can use getch() from conio.h. Just like this:
您也可以使用来自conio.h的getch()。就像这样:
...includes, defines etc
void main()
{
//operator
getch(); //now this function is waiting for any key press. When you have pressed its just //finish and next line of code will be called
}
So, because UNIX does not have conio.h, we can simulate getch() by this code (but this code already written by Vinary, my fail):
因为UNIX没有conio。h,我们可以通过这个代码来模拟getch()(但是这个代码已经由Vinary编写,我的失败):
#include
#include
#include
int mygetch( ) {
struct termios oldt,
newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
-1
#include
using namespace std;
int main () {
bool boolean;
boolean = true;
if (boolean == true) {
cout <<"press any key to continue";
cin >> boolean;
}
return 0;
}
-2
If you look up kbhit() function on MSDN now, it says the function is deprecated. Use _kbhit() instead.
如果您现在在MSDN上查找kbhit()函数,它表示该函数已被弃用。使用_kbhit()。
#include
int main()
{
_kbhit();
return 0;
}
-2
You can use Scanner variable, and use the HasNext() method. Then break it and exit using a function exit();
您可以使用扫描器变量,并使用HasNext()方法。然后使用函数exit()将其断开并退出;
import java.util.Scanner;
public class exit_onClick {
public static int exit()
{
return 0;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Press Any Key to EXIT....");
int c=0;
while(scan.hasNext())
{
c++;
if(c==1)
break;
}
exit();
}
}
-4
Just use the system("pause");
command.
只使用系统(“暂停”);命令。
All the other answers over complicate the issue.
所有其他的答案都把这个问题复杂化了。