Как скрыть строку: для продолжения нажмите любую клавишу?

Я новичок. Интересуюсь, как, с помощью какой команды в C++, скрыть строку в MS DOS: ,,Для продолжения нажмите любую клавишу» ?
Лучшие ответы ( 1 )
| Здесь вы можете заказать любую студенческую или школьную работу. |
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
Как заменить «Для продолжения нажмите любую клавишу.» на другую фразу?
Как заменить "Для продолжения нажмите любую клавишу. " на другую фразу?
В консоли выводится только «Для продолжения нажмите любую клавишу . . .»
Написал первую программу "Hello world!" в Visual Studio 2017. Компилируется, но при запуске.
При просмотре результата, выводится только «Для продолжения нажмите любую клавишу»
Здравствуйте, пользуюсь компилятором Dev-C++. Для теста решил вывести "Hello World", вывелось.
Котовчанин
942 / 482 / 200
Регистрация: 16.02.2010
Сообщений: 3,338
Записей в блоге: 37

Сообщение было отмечено frid как решение
Решение
Если Вам нужно задержать при этом экран — то почитайте про getch().
![]()
![]()
2021 / 1348 / 385
Регистрация: 16.05.2013
Сообщений: 3,482
Записей в блоге: 6
Убрать команду
system("pause");
Если эта хрень встроена в IDE то см. настройки самой среды.
Сообщение от frid 
с помощью какой команды в C++, скрыть строку в MS DOS: ,,Для продолжения нажмите любую клавишу» ?
хД обычно просят как сделать чтобы результат было видно, а такое — впервые
| Меню пользователя @ aLarman |
Неэпический
17859 / 10625 / 2051
Регистрация: 27.09.2012
Сообщений: 26,712
Записей в блоге: 1
Сообщение от frid 
Интересуюсь, как, с помощью какой команды в C++, скрыть строку в MS DOS: ,,Для продолжения нажмите любую клавишу» ?
system ( "pause >> NUL" ) ;
Регистрация: 14.02.2013
Сообщений: 6
Всем спасибо делал:1) подключил:#include
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь

Убрать вывод фразы «Для продолжения нажмите любую клавишу» по окончании работы программы
Ребят как убрать написанное "Для продолжения нажмите любую клавишу" .
Написал программу горит просто экран и нажмите любую кнопку для продолжения
Ввести в память ПЭВМ с клавиатуры три строки, в каждой из которых не более 80 символов. Написать.

Подскажите как сделать, например «для продолжения нажмите клавишу х» и дальше выводится результат с шагом заданым пользователем
Подскажите как сделать, например "для продолжения нажмите клавишу х" и дальше выводится результат с.

Как убрать надпись «Дла продолжения нажмите любую кнопку» ?
Написал свой первый код чуть больше чем "Hellow world". Приложение консольное. Без интерфейса.
Или воспользуйтесь поиском по форуму:
C++: execute a while loop until a key is pressed e.g. Esc?
Does anyone have a snippet of code that doesn’t use windows.h to check for a key press within a while loop. Basically this code but without having to use windows.h to do it. I want to use it on Linux and Windows.
#include #include int main() < bool exit = false; while(exit == false) < if (GetAsyncKeyState(VK_ESCAPE)) < exit = true; >std::cout std::cout
asked Apr 1, 2013 at 4:08
pandoragami pandoragami
5,425 15 15 gold badges 69 69 silver badges 117 117 bronze badges
s/GetAsyncKeyState(VK_ESCAPE)/GetAsyncKeyState(VK_ESCAPE) & 0x8000 .
Apr 1, 2013 at 4:11
@chris I’m sorry I don’t understand what you mean.
Apr 1, 2013 at 4:11
Do you want a specific key to be pressed or any key?
Apr 1, 2013 at 4:12
@Aswin Any key is fine.
Apr 1, 2013 at 4:12
It means you should replace the first with the second. It’s specified that if the key is down, the MSB is on. Standard C++ doesn’t have a portable solution for this that I know of. I suppose a multithreaded cin.get() kind of works, but I’m very iffy with doing that.
Apr 1, 2013 at 4:13
5 Answers 5
#include #include int main() < char c; std::coutstd::cout
answered Apr 1, 2013 at 4:26
Nasir Mahmood Nasir Mahmood
1,485 1 1 gold badge 13 13 silver badges 18 18 bronze badges
So getch() just returns EOF with no input? Isn't getchar() more portable?
Sep 22, 2014 at 13:23
Your best bet is to create a custom "GetAsyncKeyState" function that will use #IFDEF for windows and linux to choose the appropriate GetAsyncKeyState() or equivalent.
No other way exists to achieve the desired result, the cin approach has its problems - such as the application must be in focus.
answered Apr 1, 2013 at 4:23
user2180519 user2180519
Thats what I thought too. I don't like using #ifdef _WIN32 #endif #ifdef linux #endif but theres no other way I guess.
Apr 1, 2013 at 4:24
Another solution would be to have the implementation of such a function in two files, implement_linux.cpp and implement_windows.cpp for example, and simply compile and link with one of them depending on the system you're using. No #ifdef needed !
Apr 1, 2013 at 4:26
char c; while (cin >> c)
ctrl-D terminates the above loop. It will continue so long as a char is entered.
answered Apr 1, 2013 at 4:14
gongzhitaao gongzhitaao
6,596 3 3 gold badges 36 36 silver badges 45 45 bronze badges
I'm on windows XP right now. Tried it and it just hangs. I guess its normal.
Apr 1, 2013 at 4:17
@lost_with_coding, Yes, all input in standard C++ is blocking. I'm not particularly confident in hacks to change that behaviour.
Apr 1, 2013 at 4:17
@chris So there is no way to do this on windows without windows.h ?
Apr 1, 2013 at 4:18
@lost_with_coding sorry for the misleading, windows does not have an equivalent key to ctrl-d .
Apr 1, 2013 at 4:19
I guess I could do #ifdef _WIN32 #endif #ifdef linux #endif
Apr 1, 2013 at 4:23
//simplest.
#include #include using namespace std; int main() < char ch; bool loop=false; while(loop==false) < coutcout
answered Oct 11, 2015 at 17:11
1 1 1 bronze badge
//its not the best but it works #include #define WINVER 0x0500 #include #include #include int main() < char c; std::coutstd::cout
answered Jun 17, 2016 at 18:45
Not Larangi Not Larangi
Please do not post the same answer to multiple questions. If the same information really answers both questions, then one question (usually the newer one) should be closed as a duplicate of the other. You can indicate this by voting to close it as a duplicate or, if you don't have enough reputation for that, raise a flag to indicate that it's a duplicate. Otherwise, be sure you tailor your answer to this question and don't just paste the same answer in multiple places.
Jun 17, 2016 at 19:07
- c++
- while-loop
- exit
- multiplatform
- onkeypress
How to simulate "Press any key to continue?"
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. Here is my code:
char c; cin>>c; cout
but this is not working, because it only move to next line when I input some character and then press 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?
7,350 17 17 gold badges 41 41 silver badges 61 61 bronze badges
asked Sep 19, 2009 at 19:35
itsaboutcode itsaboutcode
24.7k 45 45 gold badges 112 112 silver badges 156 156 bronze badges
As far as I know, the problem is, that your shell is waiting for you to press ENTER or EOF and then will let your program take care of whatever is in the buffer, or something like this. Maybe somebody with some more knowledge could provide a real explanation. But I think it is not as easy as it first appears.
Sep 19, 2009 at 21:02
By far the easiest way to handle this, and the only portable way, is to change your prompt from “Press any key to continue” to “Press the Enter key to continue”.
Feb 23, 2012 at 4:44
@Lucas - I am using mac with xcode.
Feb 23, 2012 at 19:25
@Lucas: It's not the shell, it's the program itself.
Feb 23, 2012 at 19:25
@KeithThompson: This is more than two years ago, but I think I was trying to make the point that the input queue doesn't get handled by the user process but inside the Kernel.
Feb 24, 2012 at 3:13
15 Answers 15
system("pause");
and on Mac and 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
441 6 6 silver badges 18 18 bronze badges
answered Sep 21, 2009 at 3:02
user176379 user176379
system calls external program. You don't have to call external program to wait for any key! It's like calling another person to turn on your computer when you're sitting in front of it - this is slow solution.
Aug 25, 2014 at 9:51
True, but it's only one line long! Sometimes it's just not worth the effort to save the computer some cycles.
Nov 24, 2014 at 17:02
Forget slow, it calls the first program named "pause" it happens to find in PATH, and gives it the calling program's privilege level. Even if you're a student just testing your own code, it's still a massive security risk.
Dec 14, 2014 at 11:11
@XDfaceme - pause is an actual program that system() asks windows to run. If however, there's another program called 'pause' and windows finds that program first, it will run it instead. I suppose I might've overblown the significance a little, but it's still easier to just use cin.get() and hit return to pause/unpause a program
Jan 27, 2015 at 23:32
I am not a fan of absolutes. Making a blanket statement that system("pause") is a security risk and that it is bad even when testing your own code is blowing things way out of proportion here. cin.get() might be the right solution, but it does not solve the question that was being asked. cin.get() only responds after "enter" or "return" are pressed. The question specifically was to respond to any key press. system("pause") does exactly that. First of all, the only place where I have seen this as useful is in a dev class when debugging from Visual Studio, so I think that system("pause") works
Sep 4, 2017 at 23:07
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 it. Quoted from here, here it is:
#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
gcc -o kbhit kbhit.c
./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?
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.
Как продолжить действия программу в С++? Недавно начал программировать в С++ и столкнулся с проблемой.
Как сделать так, что после привет в консольном приложении я смог сразу же задать вопрос как дела?
После слова привет у меня с++ сразу выдает ответ привет! и пишется для продолжения нажмите любую клавишу, а мне скажем так, надо дальше задавать вопросы приложение. как то так
#include
using namespace std;
int main() setlocale(LC_ALL, "Russian");
int привет = 0, как_дела = 3;
Лучший ответ
верх я не докопировал так что верх оставляй я просто покажу как должно работать.
int main() setlocale(LC_ALL, "Russian");
int privet = 0, kak_dela = 0; // две палочки это коментарий че хочешь пишешь
// но код работать будет.
cout cin >> privet; // это ввод пользователя с клавиатуры. в privet
cout cin >> kak_dela; // ввод пользователя в переменную kak dela.
if (privet==1 ) // if (условие) privet сравнивание с 1 то есть прив == 1
cout >
if (kak_dela==2) // сравнение переменной kak dela с 2 kak dela == 2
< // если = то пишешь == два знака ==.
cout > // в общем = это знак присвоения а два == это знак равно
system("pause");
return 0;
>
надеюсь ты все понял. в общем задавай вопросы тут и открывай книжки или что то еще по понятнее которые или повторяй все по книге повторяй до тех пор пока не поймешь и тут спрашивай.
Остальные ответы
Ну и вписывай, что тебе надо, перед system("pause");
Только используй имена переменных на латинице - не маленький 😉