This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to stop C++ console application from exiting immediately?
I have the following console program:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
cout<<"Enter a";
cin>>a;
cout<<"Enter b";
cin>>b;
int result = a*b;
cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
return 0;
}
Once i run the program,it accepts the input but exits before i can have a look at the results.What do i need to do for the program not to exit before i can take a look at the results?.
BTW, you've already calculated the value of result before you've gotten your input for a and b, so the value of result will either be 0 if your compiler assembles code that zero-initializes any variables declared on the stack, or will just be some random value. In fact, you really don't need to even declare result ... you can calculate it's value in the cout statement. So you can adjust your last line so it looks like this:
cout << "You entered" << a <<"and you entered"<< b
<< "Their product is" << (a*b) << endl;
To stop the program from exiting, you can grab another char from stdin. So you can do the following:
cout << "Press any key to exit..." << endl;
char extra;
cin >> extra;
What about adding system ("pause"); before return 0; statement?
Use getche() ,getch() or any character based input function.
int main()
{
int a;
int b;
int result = a*b;
cout<<"Enter a";
cin>>a;
cout<<"Enter b";
cin>>b;
cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
getch(); //use this.It would wait for a character to input.
return 0;
}
And generally we use Enter to exit the program whose ASCII value is fetched by it .But since it is of no use to us not storing it in a variable.
You could ask for more feedback
cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
char stop;
cin >> stop;
I like to use getch() from conio.h when I'm on Windows, but that's not quite portable :/
Windows:
//1
system ("pause");
//2
#include<conio.h>
_getch();
.NET (Windows):
System::Console::ReadLine();
Overall:
#include <cstdlib.h>
return EXIT_SUCCESS;
Related
This question already has answers here:
Using fflush(stdin)
(7 answers)
Closed 3 years ago.
I wrote this simple addition software, in which I wanted the addition to end when the user entered 'n'. My current code works just fine. But I made two more variations of the same code, one worked, and one gave me an error. Can anyone tell me what is happening exactly in each case?
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
cin>>a;
b+=a;
}while(getchar()!='n');
cout<<b;
//works just fine
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
fflush(stdin);
cin>>a;
b+=a;
}while(getchar()!='n');
cout<<b;
//this one works too
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
a=getchar();
b+=a;
}while(a!='n');
cout<<b;
//doesn't work
I wanna know why fflush(stdin) have no effect on the code. If I just keep writing my input like "20, 30, 50, n" instead of "20, y, 30, y, 50, n" I get the same result in both working codes. Why does this happen?
First of all, it is best to use C++ standard input and output std::cin and std::cout respectively.
The main problem with your code is that it conflicts with types you want:
You want to add integers int together and to see if the input is the character char 'n'.
What's happening is the legacy C fflush(stdin) "flushes" or clears the standard input stream buffer (read more here: https://www.google.com/amp/s/www.geeksforgeeks.org/use-fflushstdin-c/amp/) and getchar() receives character input from the user. getchar() returns a character and by deduction, your code transmutes that input into its integral int ASCII-ANSI numerical integral equivalent.
This means that on the third version, when you input "30", what actually is collected is '3' and without flushing the buffer, the next input is considered '0' causing a problem.
I suggest you use a control structure to check if the user wants to continue before receiving input to add:
int a = 0, b =0;
char c = 0; // for y/n responses
std::cout << "Welcome to my ... "; //just finish this string
do{
std::cout << "input integer: "; // for better formatting leave at least one space after the colon
std::cin >> a;
b += a;
std::cout << "Continue? n to stop: "
std::cin >> c;
} while (c != 'n')
std::cout << "Added: " << b;
I have a c++ program where I need to iterate through a string and print the characters. I get the correct output but along with the output I get some garbage values(garbage value is 0). I don't know why i get those values? Can anyone help me with that?
#include <iostream>
using namespace std;
int number_needed(string a) {
for(int i=0;i<a.size();i++)
{
cout<<a[i];
}
}
int main(){
string a;
cin >> a;
cout << number_needed(a) << endl;
return 0;
}
sample Input
hi
Output
hi0
The behaviour of your program is undefined. number_needed is a non-void function so therefore it needs an explicit return value on all program control paths.
It's difficult to know what you want the cout in main to print. Judging by your question text, you may as well change the return type of number_needed to void, and adjust main to
int main(){
string a;
cin >> a;
number_needed(a);
cout << endl; // print a newline and flush the buffer.
return 0;
}
The problem is with this line:
cout << number_needed(a) << endl;
Change it to just:
number_needed(a);
The problem is that number_needed() is outputting each letter of the string, but after that, you're outputting the value returned by number_needed(), which is 0.
my program is a calculator that currently only does addition and subtraction, but when i input a large number it starts flashing and scrolling. it works fine for small numbers. the program isn't long so here it is. a youtube video of the problem https://youtu.be/Fa03WtgXoek
#include <iostream>
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
return a;
}
int add()
{
int x = GVFU();
int y = GVFU();
int z = x + y;
std::cout <<z <<std::endl;
return 0;
}
int subtract()
{
int x = GVFU();
int y = GVFU();
int z = x - y;
std::cout <<z << std::endl;
return 0;
}
int main()
{
for ( ; ; )
{
std::cout << "enter 1 for addition and 2 for subtraction";
int c;
std::cin >> c;
if (c==1)
{
add();
}
if (c==2)
{
subtract();
}
std::cout << "press 1 to end";
int e;
std::cin >>e;
if (e==1)
{
return 0;
}
}
}
If you try to read a value from cin and the value read doesn't match the expected format, it causes the stream to fail and all future read operations will instantly return without reading anything.
Independently, in C++ integer values for the int type have a minimum and maximum possible value that depends on what compiler and system you're using. If you exceed that value when entering a number, cin will consider it a failed read.
Putting this together, once you enter a value that's too large, the program will keep running through the main loop in your program, prompting for a value, instantly returning without actually getting user input, then calculating garbage values.
To fix this, you'll need to either (1) just hope the user doesn't type in anything unexpected or (2) get user input more robustly. There are a number of good explanations about how to do option (2) here on Stack Overflow, and now that you know what the root cause of the issue is you can hopefully get the code fixed and working!
Use
std::cout << std::numeric_limits<int>::max() << std::endl;
and include #include <limits> and you will find out max int value on your machine.
int on your system is likely a 32-bit signed two's complement number, which means the max value it can represent is 2,147,483,647.
If you add bigger number stream will fail and all next read operations will return without reading anything.
Use unsigned long long which will allow you to insert bigger numbers.
You are taking your inputs as " int " and value range for int is between -2,147,483,648 to 2,147,483,647.
Which means that if you exceed this value 2,147,483,647 it can not be stored as an integer(int) type.
You should probably use Long data type for such large numbers.
You can add a following check in your code if the user input more than int limit
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input " << endl;
}
return a;
}
I would also add exit if invalid number
#include <iostream>
#include <cstdlib>
using namespace std;
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input " << endl;
std::exit(EXIT_FAILURE);
}
return a;
}
Note: You could also more info instead of just "Invalid input "
Output like size or limit info
enter 1 for addition and 2 for subtraction1
enter number4535245242
Invalid input
Program ended with exit code: 1
I have made a simple program in C++ and this is the code:
#include <iostream>
using namespace std;
int main()
{
int number;
int square;
number = 5;
square = number * number;
cout << "The square is ";
cout << square;
return 0;
}
what it does is basically taking the integer "5" and get the square value on the screen and so on...
my question is:
how can I make the program take any value from the user instead of storing a value in the memory?
than Q.
Your code makes use of cout to print. C++ makes cin available for input from the console:
int x;
cin >> x;
"An example is worth a thousand words..."
Well cout takes some var. from memory and prints it out on the screen, right?
Well, cin does the exact opposite, it takes in some value from the keyboard and puts it in your memory..
You have to take in the value with the help of cin command, like this:
int a; //lets say you have a variable
cout << "Enter a value here: "; //prompts the user to enter some number
cin >> a; //this line will allow the user to enter some value with the keyboard into this var.
int square = a * a;
cout << "The square is: " << square;
Hope it helps...
Just replace:
number = 5;
with:
cout << "What's the number? ";
cin >> number;
You already know how to use cout to generate output, this simply uses cin to retrieve input.
Keep in mind that, while this may be okay for small test programs or learning, data input in real programs tends to be a little more robust (such as if you enter the string xyzzy when it's trying to input an int variable).
I have posted the relevant code below. When I compile the program, it runs and reaches the point where it waits for the input. I type in an integer and press ENTER, but the code never continues. How would I go about correcting this?
int i;
cout << "Please input column to sort by: ";
cin >> i;
Well, first of all, what you posted above won't compile. Try this instead:
#include <iostream>
int main(int argc, char *argv[]) {
int i;
std::cout << "Please input column to sort by: ";
std::cin >> i;
std::cout << "You entered: " << i << "\n";
return 0;
}
Compile it with g++ -O3 thefile.cpp, assuming the file is called "thefile.cpp".
If it doesn't work then there is a serious issue going on. If it does you should be able to diagnose your issue further.
If you use visual studio 2010 try this:
#include<iostream>
using namespace std;
int main(){
int i;
cout<<"Please input column to sort by: ";
cin>>i;
cout<<"Your input the number: "<<i<<"\n\n";
system("pause");
return 0;
}