Why does program close without pausing?(C++) [duplicate] - c++

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 3 years ago.
I have written a C++ program to test compound inequalities/equalities.
When I run it in the IDE, it stops before it closes, but when I actually compile and run it as a executable, the console closes before I can read the output, even though I have specifically put a line at the end to pause it.
The code is included below:
#include <iostream>
using namespace std;
int main()
{
int x;
int y;
int a;
int b;
int test1;
int equality;
int test2;
bool et1;
bool lt1;
bool mt1;
bool et2;
bool lt2;
bool mt2;
bool t1;
bool t2;
cout << "What would you like to do? \n 1) Test two conditions are met \n 2) test if one condition is met out of two \n";
cin >> equality;
cout << "what would you like to test for the first pair of numbers? \n 1) if x == y \n 2) if x < y \n 3) if x > y \n";
cin >> test1;
cout << "what would you like to test for the second pair of numbers? \n 1) if x == y \n 2) if x < y \n 3) if x > y \n";
cin >> test2;
cout << "Choose the first number to the first inequality/equality \n";
cin >> x;
cout << "Choose the second number to the first inequality/equality \n";
cin >> y;
cout << "Choose the first number to the second inequality/equality \n";
cin >> a;
cout << "Choose the second number to the second inequality/equality \n";
cin >> b;
if (test1 == 1 && x == y){
et1 = true;
}
else if (test1 == 2 && x < y) {
lt1 = true;
}
else if (test1 == 3 && x > y) {
mt1 = true;
}
else if (test2 == 1 && a == b) {
et2 = true;
}
else if (test2 == 2 && a < b) {
lt2 = true;
}
else if (test2 == 3 && a > b) {
mt2 = true;
}
if (lt1 == true || et1 == true || mt1 == true) {
t1 = true;
}
if (lt2 == true || et2 == true || mt2 == true) {
t2 = true;
}
if (equality = 1 && t1 == true && t2 == true) {
cout << "this compound and inequality is true";
}
else if (equality = 2 ) {
if (t1 == true || t2 == true) {
cout << "this compound or inequality is true";
}
cout << "this compound inequality is true";
}
std::cin.get();
return 0;
}

You can include the header file "conio.h" and do a getch() call whenever you want a pause in your program
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
cout<<"After printing this there will be a pause.Press any character to contine\n";
getch();
cout<<"Code ends\n";
return(0);
}

Related

Why does cin.peek() == '\n' work for '+' and '-', but not for '*', '/', and '^'?

I'm doing a calculator in replit. Why does my cin.peek() == '\n' work when I enter + and - but it doesn't work when I enter *, /, or ^?
#include <iostream>
#include <math.h>
#include <vector>
#include <istream>
using namespace std;
float hasil;
vector<float> num;
vector<char> op;
void calc(float x, float y, char z) {
if (z == '+') {
hasil = x + y;
}
else if (z == '-') {
hasil = x - y;
}
else if (z == '*') {
hasil = x * y;
}
else if (z == '/') {
hasil = x / y;
}
else if (z == '^') {
hasil = pow(x,y);
}
else {
cout<< "wrong operator";
}
}
void input () {
float in;
char ch;
for (int i = 0;;i++) {
if(cin.peek() == '\n') {
break;
}
else if(cin.peek() == '+') {
op.push_back('+');
}
else if(cin.peek() == '-') {
op.push_back('+');
}
else if(cin.peek() == '*') {
op.push_back('*');
}
else if(cin.peek() == '/') {
op.push_back('/');
}
else if(cin.peek() == '^') {
op.push_back('^');
}
cin >> in;
num.push_back(in);
}
for (auto i = num.begin(); i != num.end(); ++i) {
cout << *i << " ";
}
for (auto i = op.begin(); i != op.end(); ++i) { //this is just so I can see what is in the vectors
cout << *i << " ";
}
calc(num.at(0),num.at(1),op.at(0));
for (int i = 2; i < num.size(); i++)
calc(hasil,num.at(i),op.at(i-1));
}
int main() {
cout << "rumus = ";
input();
cout << " = ";
cout << hasil;
}
When I enter 1+2+3+4 it works fine, but the for loop doesn't break when I, for example, enter 1/3 or 2/3.
if(cin.peek() == '\n') {
break;
}
Why doesn't this run when there is a /, *, or ^ in what I enter?
Sorry if I have bad grammar. English is not my first language, and I am very new to C++ and coding in general. I don't know much about coding.
If you enter "4-2", you might notice that the numbers are 4 and -2, and the operator is +.
It produces the correct result by mistake because of if(cin.peek() == '-') { op.push_back('+'). (Copy-paste bug?)
You never actually read an operator, you only read floats.
"+2" and "-2" are valid inputs when reading a number, and peek leaves the character in the stream.
Thus, "1+2" is read as "1" and "+2", "1-2" as "1" and "-2".
None of the other operators can prefix a number, so in all those cases the stream enters an error state, never reads anything, and you're stuck in a loop.
I will leave fixing the bug as an exercise.

executing ls command and printing output it

so i have made this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while(true)
{
string x;
string y;
string an1[3] = {"quit","exit","leave"};
double ver = 0.1;
cout << "basic0.1% ";
cin >> x;
if (x == "upgrade")
{
system("yay -Syyu");
}
else if (x == "install")
{
cout << "What do you want to install?" << "\n";
cin >> y;
system(("sudo yay -S " + y).c_str());
}
else if (x == "version")
{
cout << "version: " << ver << "\n";
}
else if (x == "clear")
{
system("clear");
}
else if(x == "quit" || "leave" || "exit")
{
break;
}
else if(x == "ls")
{
}
}
return 0;
}
and in the else if(x == "ls"){} i wanted to show the output of the command,i tried putting system("ls");
but it just exits the program.
btw this should be a little terminal emulator for linux but i am not sure yet,i am just having some fun.
system("ls"). works fine. Your problem is this:
else if(x == "quit" || "leave" || "exit")
{
break;
}
Let's say you type ls. Then x contains the string "ls". x == "quit" is false because you didn't type quit. "leave" is true because it's a non-null pointer. "exit" is true because it's a non-null pointer. false || true || true is true, so the program quits.

C++ Newbie questions

My task:
Write the following program: The user is asked to enter 2 floating point numbers (use doubles). The user is then asked to enter one of the following mathematical symbols: +, -, *, or /. The program computes the answer on the two numbers the user entered and prints the results. If the user enters an invalid symbol, the program should print nothing.
My code:
#include <iostream>
using namespace std;
int introducir()
{
int a;
cin >> a;
return a;
}
bool simbolo(char x)
{
if (x == '+')
return true;
if (x == '-')
return true;
if (x == '*')
return true;
if (x == '/')
return true;
return false;
}
void operar(char x, int a, int b)
{
if (x == '+')
cout << a+b;
if (x == '-')
cout << a-b;
if (x == '*')
cout << a*b;
if (x == '/')
cout << a/b;
else cout << "INVALID OPERATION SIMBOL";
}
int main()
{
cout << "insert 2 numbers"<< endl;
int a =introducir();
int b= introducir();
cout << "introduce one of these simbols : +,-,* o /." << endl;
char x;
cin >> x;
bool primo= simbolo(x);
{
if (primo) {
cout << "simbol is valid" << endl;
} else {
cout << "invalid simbol" << endl;
}
cout << "operation result is:";
}
operar(x,a,b);
}
If the symbol is not in (+,-,*,/), I want it to return a message "INVALID OPERATION SIMBOL"; however it returns it even if the symbols are valid. How do I fix that?
The way you've written it, the else only applies to the final if.
Change to
if (x == '+'){
cout << a+b;
} else if (x == '-'){
cout << a-b;
} else if (x == '*'){
cout << a*b;
} else if (x == '/'){
cout << a/b;
} else {
cout << "INVALID OPERATION SIMBOL";
}
and similar for the other if statements. (You could even consider refactoring to a switch block.) The braces are not entirely necessary but I've put them in for clarity.

Storing multiple user input into an array

I am currently working on a program for a project, that asks for the user to enter the specific sport they want to play and their age for reservations at a recreation area. I am confused on how to store their sport and age into an array so that it can be displayed later in the program, if they select to view all reservations made by one or more users. If anyone could help me with figuring out how to store a single or multiple user input into an array so that it can be displayed later in the program that would be great!
#include <iostream>
#include <string>
using namespace std;
int main()
{
char t; // Type of sport selected
char g, G; // Gliding
char h, H; // Hang-gliding
char f, F; //Flying
int a; // Age of patron
double x; // Rates
int s; // Selection from menu
int i; // Arrays variable
int num;
char sport[100]; // Array for all sports of patrons
int age[100]; // Array for all ages of patrons
cout << "Please pick from the following menu" << endl;
cout << "1. Add a new reservation" << endl;
cout << "2. Print all reservations" << endl;
cout << "3. Print all reservations for a given sport" << endl;
cout << "4. Quit" << endl;
cin >> s;
for (i = 0; i < num; ++i)
if (s == 1) {
cout << "Please enter f/F for flying, g/G for gliding and h/H for hang-gliding" << endl;
cin >> t;
getline (cin, sport[i]);
cout << "Please enter the age of patron, minimum age is 16" << endl;
cin >> a;
if ((t == 'f' || t == 'F') && (a <= 25)) {
x = 68.95;
}
else if ((t == 'g' || t == 'G') && (a <= 25)) {
x = 73.95;
}
else if ((t == 'h' || t == 'H') && (a <= 25)) {
x = 99.95;
}
else if ((t == 'f' || t == 'F') && (a > 25)) {
x = 55.95;
}
else if ((t == 'g' || t == 'G') && (a > 25)) {
x = 65.95;
}
else if ((t == 'h' || t == 'H') && (a > 25)) {
x = 92.95;
}
cout << "The insurance rate is $ " << x << endl;
}
else if (s == 2) {
cout << "A patron aged " << a << " reserved a session of " << t << endl;
}
else if (s == 3) {
}
else if (s == 4);
return 0;
You should make a class Patron that contains the multiple informations, then make an array of type Patron instead of multiple arrays:
class Patron
{
//data for each patron...
};
in main:
Patron patrons[...];
You could also use dynamic containers, like vector instead of an array.
std::vector<Patron> patrons;

C++ Boolean function returning 56

I have a function to return a bool:
bool restart()
{
std::string answer;
bool answered = false;
while(answered == false)
{
cout << endl << endl << "Do you want to play again? y/n : ";
cin >> answer;
if(answer == "y" || answer == "Y" || answer == "1" || answer == "yes")
{return true;}
if(answer == "n" || answer == "N" || answer == "0" || answer == "no")
{return false;}
}
}
When I call it using:
cout << restart();
I get the output:
Do you want to play again? y/n : y
56
Can anyone see how to fix this strange problem?
Thanks in advance.
My WIP code as it is now:
#include <iostream>
#include <cstdlib>
using namespace std;
void drawScreen(int grid[3][3]); //
int movef(int grid[3][3], bool playersMove);
int updateGrid(int grid[3][3], int move, bool playersMove);
bool hasWon(int grid[3][3]);
bool swapMover(bool playersMove); //
bool restart();
void endGame();
int main()
{
int grid[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
bool appRunning = true, gameRunning = true, playersMove = true;
int move;
// tests //
std::cout << restart();
// tests //
//while(appRunning == true)
//{
// while(gameRunning == true)
// {
// drawScreen(grid);
// move = movef(grid, playersMove);
// grid[3][3] = updateGrid(grid, move, playersMove);
// drawScreen(grid);
// gameRunning = hasWon(grid);
// playersMove = swapMover(playersMove);
// }
// appRunning = restart();
//}
//endGame();
}
void drawScreen(int grid[3][3])
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(grid[i][j] == 10){cout << "X ";if(j == 2){cout << endl << endl;}}
if(grid[i][j] == 11){cout << "O ";if(j == 2){cout << endl << endl;}}
if(grid[i][j] != 10 && grid[i][j] != 11){cout << grid[i][j] << " ";
if(j == 2){cout << endl << endl;}}
}
}
}
int movef(int grid[3][3], bool playersMove)
{
return 0;
}
int updateGrid(int grid[3][3], int move, bool playersMove)
{
return 0;
}
bool hasWon(int grid[3][3])
{
return false;
}
bool swapMover(bool playersMove)
{
if(playersMove == true){return false;}
if(playersMove == false){return true;}
}
bool restart()
{
std::string answer;
bool answered = false;
while(answered == false)
{
cout << endl << endl << "Do you want to play again? y/n : ";
cin >> answer;
if(answer == "y" || answer == "Y" || answer == "1" || answer == "yes")
{return true;}
if(answer == "n" || answer == "N" || answer == "0" || answer == "no")
{return false;}
}
}
void endGame()
{
}
[This is somewhat of a repost of my comment since OP said it solved his problem]
You have no return value defined outside of the while loop. If somehow you get outside of it, you do not return a value (though I have no idea what behavior is expected or even if any behavior is expected in this case)
To make my answer a bit more thorough, I have found this:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
OK, I'm making a guess. Your original code has the line
grid[3][3] = updateGrid(grid, move, playersMove);
And your grid definition is
int grid[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
This means that your are writing out of the array bounds. This is undefined behavior.
Please correct this and check if your program works as expected.
I used the mingw32 compiler, when using g++ 4.8 it works fine. It seems to be a compiler error. (thanks to grizzly)