c++ getchar works in vs 2010, doesn't in 2012 - c++

Why the program just exits, in vs 2012, while in 2010 does it wait for my input?
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string path = "c:\somepath";
cout << "Path is" + path << endl;
getchar();
return 0;
}

The getchar() function is not used in the program flow and only the side effect of waiting for input is used in your case. Instead of hacking your program to avoid closing the window you should use the proper way to keep it open.
Choose one of:
Command window
open a command prompt
navigate to the folder where you want your program to execute
type the path to the .exe and hit Enter. The command prompt is still open after execition of your program and there is not need for getchar().
Start without debugging
just use the menu item Debug->Start Without Debugging. The new console window is still open after execition of your program and there is not need for getchar().
Start with debugging
Set a breakpoint at the closing '}' of your main function.
use the menu item Debug->Start. The debugging session is still active and the window for your console program is still open. There is not need for getchar().
Why you should avoid getchar() to keep a window open?
It's a hack that depends on the program before. There can be some characters in the input buffer a s pointer out here: getchar() doesn't work well?
Your program can't be used in batch file if you come beyond the phase where you try to learn C or C++.
It's not necessary.

Related

Why is the console asking for input even though there is no input in code?

I'm taking an online computer science class for grade 12 and we're using c++. I've never touched c++ and I'm starting to wish I never had. The teacher is comparing c++ to java (a language I can use perfectly fine) and we're currently learning how to input and output strings and chars. The simple practice problem was
Use one of fputc(), putc(), or putchar() to print your name one char at a time.
Since I have no clue how to use fputc() or putc() I decided to go with putchar()
#include <iostream>
using namespace std;
#include <stdio.h>
int main() {
cout << "My name is :" << endl;
putchar('J');
putchar('a');
putchar('c');
putchar('o');
putchar('b');
return 0;
}
I tried just using putchar(), and then added the cout, and have tried restarting eclipse, etc. but every time I run the program, the console asks for an input. There should not be an input for this program at all.
Try running your program from outside of the IDE and see what happens. When you launch a console program from inside of an IDE, a new console window is created to run the program in. When the program ends, the console window will close. Many IDEs setup the console to wait for you to press a key, giving you a chance to see the program's output, before the window closes.

cmd shell flashes across in VS code [duplicate]

Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?
If you are using Visual Studio and you are starting the console application out of the IDE:
pressing CTRL-F5 (start without debugging) will start the application and keep the console window open until you press any key.
Edit: As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem.
That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.
At the end of your main function, you can call std::getchar();
This will get a single character from stdin, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).
You need to #include <cstdio> for getchar.
The solution by James works for all Platforms.
Alternatively on Windows you can also add the following just before you return from main function:
system("pause");
This will run the pause command which waits till you press a key and also displays a nice message Press any key to continue . . .
If you are using Microsoft's Visual C++ 2010 Express and run into the issue with CTRL+F5 not working for keeping the console open after the program has terminated, take a look at this MSDN thread.
Likely your IDE is set to close the console after a CTRL+F5 run; in fact, an "Empty Project" in Visual C++ 2010 closes the console by default. To change this, do as the Microsoft Moderator suggested:
Please right click your project name and go to Properties page, please expand Configuration Properties -> Linker -> System, please select Console (/SUBSYSTEM:CONSOLE) in SubSystem dropdown. Because, by default, the Empty project does not specify it.
I usually just put a breakpoint on main()'s closing curly brace. When the end of the program is reached by whatever means the breakpoint will hit and you can ALT-Tab to the console window to view the output.
Why not just run the program from a console ie run the program from cmd.exe if you're using Windows. That way the window stays open after the program finishes.
[EDIT]: When I use KDevelop4 there is a fully fledged instance of Bash (a Linux CLI) running in a tab at the bottom of the IDE. Which is what I use in these sort of circumstances.
Before the end of your code, insert this line:
system("pause");
This will keep the console until you hit a key.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Please enter your first name followed by a newline\n";
cin >> s;
cout << "Hello, " << s << '\n';
system("pause"); // <----------------------------------
return 0; // This return statement isn't necessary
}
Call cin.get(); 2 times:
//...
cin.get();
cin.get();
return 0
}
If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.
I just do this:
//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;
Note: clearing the cin buffer and such is only necessary if you've used cin at some point earlier in your program. Also using std::numeric_limits::max() is probably better then INT_MAX, but it's a bit wordy and usually unnecessary.
Okay I'm guessing you are on Windows using Visual Studio... why? Well because if you are on some sort of Linux OS then you'd probably be running it from the console.
Anyways, you can add crap to the end of your program like others are suggesting, or you can just hit CTRL + F5 (start without debugging) and Visual Studio will leave the console up once complete.
Another option if you want to run the Debug version and not add crap to your code is to open the console window (Start -> Run -> cmd) and navigate to your Debug output directory. Then, just enter the name of your executable and it will run your debug program in the console. You can then use Visual Studio's attach to process or something if you really want to.
Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.
cin.get();
If you are actually debugging your application in Visual C++, press F5 or the green triangle on the toolbar. If you aren't really debugging it (you have no breakpoints set), press Ctrl+F5 or choose Start Without Debugging on the menus (it's usually on the Debug menu, which I agree is confusing.) It will be a little faster, and more importantly to you, will pause at the end without you having to change your code.
Alternatively, open a command prompt, navigate to the folder where your exe is, and run it by typing its name. That way when it's finished running the command prompt doesn't close and you can see the output. I prefer both of these methods to adding code that stops the app just as its finished.
Add the following lines before any exit() function or before any returns in main():
std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");
For Visual Studio (and only Visual Studio) the following code snippet gives you a 'wait for keypress to continue' prompt that truly waits for the user to press a new key explicitly, by first flushing the input buffer:
#include <cstdio>
#include <tchar.h>
#include <conio.h>
_tprintf(_T("Press a key to continue "));
while( _kbhit() /* defined in conio.h */ ) _gettch();
_gettch();
Note that this uses the tchar.h macro's to be compatible with multiple 'character sets' (as VC++ calls them).
Use #include "stdafx.h" & system("pause"); just like the code down below.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
std::cout << "hello programmer!\n\nEnter 2 numbers: ";
int x, y;
std::cin >> x >> y;
int w = x*y;
std::cout <<"\nyour answer is: "<< w << endl;
system("pause");
}
simply
#include <cstdio>
int main(){
// code...
std::getchar();
std::getchar();
return 0;
}
for some reason there is usually 1 character possible to read with getchar already in stdin when you run a program. so the first getchar reads this character, and the second getchar waits for user (your) input before exiting the program. And after a program exits most of terminals, especially on Windows close terminal immediately.
so what we aim to is a simple way of preventing a program from finishing after it outputs everything.
Of course there are more complex and clean ways to solve this, but this is the simplest.
Similar idea to yeh answer, just minimalist alternative.
Create a batch file with the following content:
helloworld.exe
pause
Then use the batch file.
See if your IDE has a checkbox in project setting to keep the window open after the program terminates. If not, use std::cin.get(); to read a character at the end of main function. However, be sure to use only line-based input (std::getline) or to deal with leftover unread characters otherwise (std::ignore until newline) because otherwise the .get() at the end will only read the garbage you left unread earlier.
This seems to work well:
cin.clear();
cin.ignore(2);
If you clear the buffer first it won't be a problem when you read the next one.
For some reason cin.ignore(1) does not work, it has to be 2.
You could always just create a batch file. For example, if your program is called helloworld.exe, some code would be:
#echo off
:1
cls
call helloworld.exe
pause >nul
goto :1
If you are running Windows, then you can do system("pause >nul"); or system("pause");. It executes a console command to pause the program until you press a key. >nul prevents it from saying Press any key to continue....
I'm putting a breakpoint at the last return 0 of the program. It works fine.
I used cin.get() and that is worked but one day I needed to use another cin.get([Array Variable]) before that to grab a ling string with blank character in middle of. so the cin.get() didn't avoid command prompt window from closing. Finally I found Another way:
Press CTRL+F5 to open in an external window and Visual Studio does not have control over it anymore. Just will ask you about closing after final commands run.
I tried putting a getchar() function at the end. But it didn't work. So what I did was add two getchar() functions one after another. I think the first getchar() absorbs the Enter key you press after the last data input. So try adding two getchar() functions instead of one
Instead of pressing the run button, press CTRL and F5 at the same time, it will give you the press any key to continue message. Or type "(warning use this only for testing not actual programs as an antiviruses don't like it!!!!)" at the end of your main function but: (warning use this only for testing not actual programs as an antiviruses don't like it!!!!)
just use cin.ignore() right before return 0; twice
main()
{
//your codes
cin.ignore();
cin.ignore();
return 0;
}
thats all
you can try also doing this
sleep (50000);
cout << "any text" << endl;
This will hold your code for 50000m, then prints message and closes. But please keep in mind that it will not pause forever.
Here's a problem, not so obvious. Somehow I had added a debug breakpoint at the very last line of my program. } Not sure how I did that, perhaps with an erroneous mouse click while jumping between different screens. I'm working in VS Code.
And when I go to debug, the system jumps immediately to that breakpoint. No error message, no interim output, nothing. I'm like, how did the program rush thru all my set breakpoints? This took too long to figure out.
Apparently the system sees that last line breakpoint as a "first" stop. The simple fix? Delete that breakpoint, doh! (insert forehead slap here.)
All you have to do set a variable for x then just type this in before the return 0;
cout<<"\nPress any key and hit enter to end...";
cin>>x;

How to prevent visual studio 2013 console window to close right after running a program? [duplicate]

This question already has answers here:
Keeping console window open when debugging
(3 answers)
Closed 8 years ago.
Hi I am using visual studio express 2013.I have never used vs before and so just to test it out I ran a simple c++ program where the user enters 2 integers and their sum is then displayed. The problem is that the console window appears and takes the inputs, but then immediately closes once the output is displayed. Please note that this happens right after all the inputs are taken and when the output is shown. Is there anyway to fix this? I have looked all over and cant find a solution. I have tried including a bunch of things such as the getch() function at the end of my program, and pressing ctrl F5 to debugg my programs,but nothing seems to work. Please help!!!
I have been using this,
int getchar ( void );
Get character from stdin
Returns the next character from the standard input (stdin).
OR
use this from process.h
system("PAUSE");
This approach is for beginners. It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program.
One decent approach is Debug.WriteLine
// mcpp_debug_class.cpp
// compile with: /clr
#using <system.dll>
using namespace System::Diagnostics;
using namespace System;
int main()
{
Trace::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );
Trace::AutoFlush = true;
Trace::Indent();
Trace::WriteLine( "Entering Main" );
Console::WriteLine( "Hello World." );
Trace::WriteLine( "Exiting Main" );
Trace::Unindent();
Debug::WriteLine("test");
}
In debug mode, Before your main return you could put a breakpoint and you will be able to see your console and the result you are waiting for.
Put
system("PAUSE");
wherever you need the program execution window to pause. If you're using int main(), usually it'll be right before you return 0

C++ , won't display last line of code

Shouldn't this work? I mean, the code is merely a test and is meant so that the dialogue goes this way : What is your name? name here, Hello name here, and yet it does not show the last line of Hello after I type in my name and click enter it just dissapears. Here is the code.
#include <iostream>
#include <string>
int main (void)
{
using std::cin;
using std::cout;
using std::string;
string name = "";
cout << "What is your name, pls?\n";
cin >> name;
cout << "\nHello " << name.c_str() << "\n";
return 0;
}
My guess is that you are running from the debugger, or double clicking the executable. In either of those cases, when the program ends, the console will close. So, the program produced output, but you just could not see it before the console closed.
Run the program from a pre-existing console so that the console remains after your program ends. Or, just whilst debugging, arrange that your program does not terminate immediately after emitting its final output. A simple way to do that is to place a break point at the end of the program.
It probably showed it right before it disappeared. If you're going to write console programs, and if you're going to send output to a console, you should run them from a console so the output has some place to go.
After you are done with your program, press Ctrl + F5 ( Run without debugging). This will prompt before closing the window and this is what you want.
Make sure you put a breakpoint before main goes out of scope. I guess your console disappears under VS?
Also, you don't need to extract the char* in the last cout statement:
cout << "\nHello " << name << endl;
Open a terminal (or a command prompt window).
Navigate to the folder that contains the executable.
Run it.
It's not disappearing. It is just running really fast.
Every IDE has a keyboard shortcut that allows you to run code and pause after the execution has finished.
This keyboard shortcut is Ctrl-F5 in Visual Studio.
I have no idea what IDE you're running, but that is your basic problem.
The other thing you can do is to test your code in ideone : ideone.com/hb4Cel (it's the same code. There is no point pasting it here)
A dirty workaround is to add something like this
cin >> name;
at the end, just before return 0;. It forces the window to wait for input (i.e. hitting return) before returning (which closes the program).
This isn't necessarily good design, but if all you want to do is run some tests then it'll do the trick.
Basically when you enter your name it displays your last line and exits after return 0.
Here are the following things to avoid that
1- use command line to run the application
Start->accessories->command prompt
Go to folder in which your application is using cd command
c:>cd c:\path\foldername
Now run the application by typing the program name e.g
c:\path\foldername>my_application.exe
It will display your last line.
2- Now if your are using microsoft visual c++ press ctrl+F5 to run your program
3- This is not recommended but you an use it as long as your are debugging then remove it from the code afterwards. Include conio.h header file and add getch(); line before return statement. It would hold the screen for you till you press a key.

"Press any button to continue" in Visual Studio Express C++?

When creating an console application (blank document) how can I get the "Press Any Button To Continue" to automatically show up?
You can add it manually with a
system("pause");
*Be carefull, this is not portable (will work on windows, but might not work elsewhere)
When you run a console program in the IDE using "Start Without Debugging" (Ctrl-F5) you get the behavior you're looking for.
For some reason, when you start the program in the IDE under the debugger ("Start Debugging" or plain-old-F5) you don't get that prompt when the program ends. If you just want to be able to see the last bit of what's in the console window when run under the debugger, you can set a breakpoint on the return from main() (or the closing brace for main()).
There is no builtin function. However you can do a simple loop with kbhit() and getch(), like so:
#include <conio.h>
void main( void )
{
// Display your message here
for(;;)
{
while( !kbhit() );
if (getch() == 0x0D)
break; // Break on ENTER
}
// Continue on here
}
Adapted from http://support.microsoft.com/kb/44895
system("pause") is definitely what you were asking for, but using it is very bad practice. Consider just using cin.get() at the end and press enter.