Get output to the Console window in C++ - c++

so i am new to C++ and I was hoping the community could help me with my homework. Now im not asking for someone to do it for me because i am very capable of doing it on my own, i am just asking for help on a particular part. So, my assignment involved making a program that could be able to find and print all of the prime numbers between 2 and 100. I have to use a double loop (its what my professor said), so i have set up an if statement to run through all of the numbers from 2 to 100 and have a second loop inside the first one to determine if the current number is a prime number and then print it. Here is where my issue comes into play, when i run it, it opens the console window and closes it so fast i cannot see if anything did print to it. So i added a break point to see if it did. When i press F5 to step into each next step, it runs through the loop once and then it starts jumping over to different windows reading the lines of different source files (i think they are source files). Eventually the console window closes with nothing printed to it, and it doesn't start the loop over again like it should. My question is this, like in Visual Basic where you can put console.readline() so a button has to be pressed from the keyboard in order to continue, how can you do the same in C++ so that after the loop to see if the number is prime ran and printed the number, the program will wait for a key to be pressed right after it was printed?
Here is my current code as follows, Thanks again for any help, I really appreciate it.
#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int counter=2;
int primeCounter=counter;
//two variables, one to keep track of the number we are one, the other to check to see if its prime.
if(counter<101)
{//I want the counter to increment by 1 everytime the loops runs until it gets to 100.
if(!(counter%(primeCounter-1)==0))//if the counter has a remainer, then it is prime
{//each time the main loop run i want this loop to run too so it can check if it is a prime number and then print it.
cout<<counter<<endl;
//if this was VB, here is where i would want to have my console.Readline()
}
else
{
}
counter+=1;
}
else
{
}

Since you're using Visual Studio you can just use Ctrl+F5 to run your program without debugging. That way the console window stays after the program's finished.
Alternatively you can run the program from the command line.
Or you can put a breakpoint on the last } of main and run it in a debugger.
It's not a good idea to add a “stop here” at the end.
If you want see each line of output as it's produced, just place a breakpoint after the output statement and run the program in the debugger, in Visual Studio keypress F5.
In passing, <stdafx.h> is not a standard header. It's in support of Visual C++ precompiled headers, which is a feature that yields quite non-standard preprocessor behavior. Better turn that off in the project settings, and remove the >stdafx.h> include.
Also
int _tmain(int argc, _TCHAR* argv[])
is a silly non-standard Microsoft-ism, at one time in support of Windows 9x, but no longer with any purpose other than vendor lock-in.
Just write standard
int main()
or with trailing return type syntax,
auto main() -> int
Finally, instead of
!(counter%(primeCounter-1)==0)
just write
counter%(primeCounter-1) != 0

cin.get() will do what you want.

In Visual Studio you can actually call system("pause"); in a place you need to suspend your app.

so i figured out my issue. First off the loop wasnt running because the first if statement didnt loop. I changes this to a while and now the output works like a charm. take a look
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int counter=2;
int primeCounter=counter;
//two variables, one to keep track of the number we are one, the other to check to see if its prime.
while(counter<101)
{//I want the counter to increment by 1 everytime the loops runs until it gets to 100.
if((counter%(primeCounter-1)==0))//if the counter has a remainer, then it is prime
{//each time the main loop run i want this loop to run too so it can check if it is a prime number and then print it.
}
else
{
cout<<counter<<endl;
}
counter+=1;
primeCounter=counter;
}
}
now i just need to polish the condition to actually figure out the prime numbers. thanks again for your help.!!!!

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.

Visual Studio CPP No Entry

I'm writing a cpp app for some while now. A few hours into the day made a small change did a build to test it and to my surprise , the build executed and nothing happened , it didn't stop executing it had a process running.
so I stopped it. and this is what I have tried.
Restrating my PC- Same Result
Making a breakpoint after the entry point. - Same Result
breakpoint didn't even hit which makes me think that the entry point just does not work.
Making a syntax error - it didn't compile and didn't run
which means my program did compile and did run before.
Completly undoing everything I did after the last running build - Same Result. it worked before but i guess not anymore
Changing my entry point from WinMain to int main() -
cmd window was created but no signs of code executing.
Doing std::cout on the first line(with cmd window) - Same Result
The only thing that worked was commenting the whole file with the entry point and just writing :
#include <iostream>
int main() {
int i;
std::cout << "hello";
std::cin >> i;
}
Anyone knows what can make such a weird behavier ?
You probably have an infinite loop in some static initialisation code.
If you hit pause in the debugger it will show you where the problem lies.

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;

C++ output screen disappears

Why does my C++ output screen disappear immediately? I'm a beginner in cpp. Can anyone help me to find the problem please?
You should either launch your application inside of a terminal, or add a line of code that waits for the input in order for the window to not close. E.g. add in the end of the function main a line:
std::cin.get();
And also add at beginning of the file the include that holds that function.
#include <iostream>
This is hard to answer since there can be many things that can cause your output box to close immediately. First try having a cout statement and then a cin statement. Something like:
cout<<"Hello"<<endl;
cin>>input>>endl;
Also make sure to have the necessary include statement at the top and whatever you want to return at the bottom.
#include<iostream>
return 0;
As you have said that you are beginner in C++, you should keep in mind ,three major things while coding in C++. You've mentioned that your screen disappears , then following things you should try.
1). in C++ conventionally main returns value of type int.And the format of your program should be like...
int main()
{
-------
//body of your program
-------
return 0;
}
If the function returns 0, that means it ran successfully.
2). You have to inlcude #include<iostream> on the top of your program.
3).check whether the IDE you are using is compatibale to your operating system or not.
Hope this will help you.

Why is terminal takes so long to start? C++

Actually i am a beginner in C++. I have been trying to write a code that can divide any number using very basic operations and producing the non-decimal quotient and remainder. But when i build and run the terminal (CodeBlocks) it takes a minute or two for the terminal to run. I have tried using arrays but no use.
Please tell me any improvement, but i donnt want to use any additional header files. Thanks in advance :)
#include <iostream>
using namespace std;
int main(){
double a, b, x, y;
int n=0;
cout<<"x\n-\ny\n\nEnter x: ";
cin>>x;
cout<<"\nEnter y: ";
cin>>y;
while (n>=0){
a=x-(y*n);
b=x-(y*(n+1));
if(b<0)break;
if(b<a) n++; }
cout<<"\nQuotient: "<<n<<"\n\nRemainder: "<<a;
}
It can't be the program itself. Check for Code Completion slowness.
Some good suggestions to add:
Turn off all Plug-ins you do not use.
Run Code::Blocks as Admin
Turn off code completion to see if the problem goes away.
Use a nightly build
It all runs fine for me.
The compiling time might be the thing that's bugging you.
Maybe don't rebuild the whole project when you just want to run the program.
I believe pressing F9 is "Build and run" and Ctrl + F10 is just "Run".
Also, n will never be less than 0 so rethink the conditional in you while loop.