The output window closes after entering the input in C - c++

I wrote program in C , but after compiling and running it the output console does not stay on after I enter anything. My program requires to enter distance and time.
My code is here:
#include <stdio.h>
int spd(int x , int y);
int main() {
int x,y;
printf("enter the distance first then time in their SI units :\n");
scanf("%d",&x);
scanf("%d",&y);
printf("the speed required is ",spd(x,y));
getch();
return 0;
}
int spd(int x , int y) {
return x/y;
}

It seems that the getch feeds on your input-buffer. When you enter your value in scanf(), the '\n' remains.
Try to put flush(stdin) after your scanf() or for now put getch () twice.

If you want to run a console program, you should run it from a console. You have written a console program -- run it from a console.
Also, you need to either flush standard out or write a newline before the getch call. Otherwise, you're waiting for a keypress before you've actually written anything.

Try including this header file : -
#include conio.h

Related

Problem when executing a simple C program in Eclipse IDE

I'm trying to run a simple C program in Eclipse and I am new to Eclipse.
When running the command I see output of the program for a very brief moment in the console, but instead for the program to wait for input, output disappears and and an empty console is shown instead. Is this a problem of the program or something related to the settings of the Eclipse IDE?
Edit: On the console menu there is a terminate button and when I pres it the output of the program shows but it doesn't wait for input and the program is terminated. Any help?
Image:
Here is the code
//The input is a series of numbers and the number X. Find
//how many times the number X is met in the series
#include<stdio.h>
int main(){
int m[20];
int n, X, cnt=0;
printf("Insert maximum length of the series (n<=20)\n");
scanf("n= %d",&n);
printf("Insert X the number you are looking for\n");
scanf("X= %d",&X);
while(n<1||n>20){
printf("Bad input, n should be between 1 and 20\n");
scanf("n= %d",&n);
}
for(int i = 0 ; i < 20 ; i++){
scanf(" %d", &m[i]);
if(m[i]==X)cnt++;
}
printf("X is found %d times\n", cnt);
return 0;
}
and here is the empty console:
Edit: I've tried rewriting the code using cout and cin but then the compiler in Eclipse complains on the line #include<iostream.h> saying that there is an unresolved inclusion. Sounds like a separate question to me.
The answer is here: click
Basically the output of the standard input output is buffered and setvbuf(stdout, NULL, _IONBF, 0); solves the problem.

Using Recursion To Print Output

#include<stdio.h>
#include<conio.h>
void main()
{
static int i=5;
clrscr();
if(--i)
{
printf("%d",i);
main();
}
getch();
}
When I am running this code, it is not giving any output and when I am removing getch() then after running when I am switching to output screen then it is showing ouput . Why?
I am using Turbo C++.
You would have seen output with debuger if you break on each iteration, but since you are obviously just executing your program what you see is the result of the last clrscr();. Since i is 0 you're not getting into the if, where the printing happens and you get right at the getch(). Hope that answers your question.
The printf function buffers output internally until either
the buffer is full
it's asked to print a newline (\n)
stdout is flushed with fflush()
You are not doing either of 2 or 3 and the buffer is surely bigger than 5 integers.
You probably want
printf("%d\n",i);
If you want the ints to be printed without a new line,
printf("%d ",i);
fflush(stdout);

C++ Program AutoClosing when Main() function completes

I wrote a simple calculator program in C++ with Code::Blocks. When I compile the program, it runs fine through Code::Blocks, and ends with a press enter to continue, and then you can exit. However, when the exe is run manually, supose for a demo, then the program works fine but rather than a press enter to continue, the program autocloses.
My main() function (all the used functions are defined, it's not becuase of that) uses iostream library:
#include <iostream>
// all the other functions are defined here
int main()
{
int input1 = getValueFromUser();
int op = getOperationFromUser();
int input2 = getValueFromUser();
int result = getAnswer(input1, op, input2 );
printResult(result);
return 0;
}
Output from Code::Blocks (after main executes, and user has seen their answer)
Process returned 0 (0x0) execution time : 3.930 s
Press any key to continue.
While running normally it simply autocloses, thereby not allowing the user to view their answer!
Thanks in advance!
If you are on Windows, here is a non-portable solution (not recommended):
printResult(result);
system("pause"); //Shows a prompt, "Press any key to continue..."
If you would like to have a portable version (recommended), use
printResult(result);
std::cin.get(); //Waits for input, press enter to continue
You could use std::cin.Ingore();
this way:
http://www.cplusplus.com/reference/istream/istream/ignore/
Your program does not have any command to wait at the end of the execution. That's why it's not waiting. It justs prints the result and return 0, ending the main function immediately.
Add getchar(); before return 0; and then the program will only exit after ENTER is pressed.
Reference: Gangadhar # StackOverflow - "Press Any Key to Continue" function in C. Sep 14, 2013.

Why does my code terminate without explanation?

I'm learning c++ again after having not touched it for the last few years, and I've run into a rather peculiar bug that I can't seem to figure out.
When I run the code below, it will accept 10 inputs as I expect it to, but immediately after the first for loop, the program exits. I have run it ingdbto try and figure out the issue, but it reported that the process 'exited normally'.
I compiled using g++ -std=c++11
#include <iostream>
#include <string>
using namespace std;
int main() {
//User inputs
string input[10];
//Get the inputs
for(int i = 0; i < 10; i++) {
//Get this input
printf("%i> ", i);
getline(cin, input[i]);
}
//The application does not make it to this point
//Collected
printf("Thank you for submitting your data.\n");
//Print inputs
for(int a = 0; a < 10; a++) {
//Show the input
printf("%i> %s\n", a, input[a].c_str());
}
}
Based on what you're describing, it sounds like stdout is not being flushed before the program ends. That's unusual; normally, stdout is automatically set up for line-buffered operation in which case it will be flushed as soon as a newline is encountered.
Your best bet is to follow #NathanOliver's advice and use cout << ... rather than printf. The printf command is a throwback to C, and you're using a C++ compiler and C++ features. In fact, you're not even including the header that's usually required for printf, so I'm a little surprised it even compiles.
FWIW, if you choose to continue using printf maybe try manually flushing stdout at the end like so:
fflush(stdout);
Your application does what is supposed to do:
Application will pause at getline() (10 times) (because getline is blocking execution), then it will do some for loops, print something and end (probably closing console window). If you add something at the end to block execution (such as cin.get(), which waits for enter key press) you will see results (because application won't terminate). If you run your code somewhere where output is not removed after program has ended you will see what was printed.

CPP printf giving no output on VS2012

I am using Microsoft Visual Studio 2012 Professional. I have a simple CPP code:
#include "stdio.h"
int main () {
int a = 0, b = 0, c = 0;
printf("\nEnter two numbers:\n");
scanf("%d %d", &a, &b);
c = a+b;
printf("\nc = %d", c);
return 0;
}
The problem I am facing is that the first printf statement is getting printed but the second one is not. The code is exiting without printing anything. However when I debug using breakpoints, the value of c is getting stored in it.
I'll take a wild guess and say you run this from your IDE.
It does print the output. But the program then ends. And it ends so fast, you cannot see the output. If you want your program to wait for you to see it, you will need to find a way to make it wait. For example with another scanf line.
As there is no standard, environment agnostic way to say "Press any key to continue", have a look here for some alternatives.
Add \n to the end of the last printf. It is implementation-defined whether the last line of output to stdout actually gets flushed , if it doesn't end in a newline.
When you use
scanf("%d %d", &a, &b);
then you should give 2 inputs separated by space or enter
scanf("%d,%d", &a, &b);
then you should give 2 input separated by comma(,).
and at last use
printf("Press any key to continue.."); getche(); instead of return;