I enter numbers in the console, press Enter, and it closes immediately | Sololearn: Learn to code for FREE!

+2

I enter numbers in the console, press Enter, and it closes immediately

#include <iostream> #include <string> #include <conio.h> using namespace std; int main() { int number; cout << "Enter a number: "; cin >> number; cout << endl; if (number > 0) { cout << "1"; } else if (number == 0) { cout << "0"; } else if (number < 0) { cout << "-1"; } getch(); return 0; }

c++

5/27/2020 6:36:26 AM

Viktor Kizera

17 Answers

New Answer

+2

Yes I have done the same thing

+4

Namit Jain (if else) is very much supported feature in C++. 👇 https://code.sololearn.com/cK46a8054SDU/?ref=app And Sin Cara M as far as problem is conserned in your code then it is nothing just that you are using outdated C++ headers(conio.h) which is no longer a standard header. Here is the fix of your code👇 https://code.sololearn.com/cz9PM5k9Nw0L/?ref=app

+3

Sin Cara M Show your exact modified code.

+2

Namit Jain And how to do it?

+2

https://code.sololearn.com/cu31FzsdphGH/?ref=app

+2

Ohhhkk thanks Arsenic for the important info👍👍

+2

Namit Jain Anything greater than 0 should be displayed "1", anything less than 0 is displayed "-1", if 0 then "0"

+2

Arsenic Thank you very much, it works☺️

+2

The problem is that getch() is taken as a part of "else" of last "else if" so when you enter a number the output is displayed and the screen is closed immediately as there is nothing to hold the output. fix - give 1 line gap before getch(). Btw the last "else if" should be else only. If the int number is not +ve, not 0 then it has to be -ve isn't it? Please note as Arsenic said conio.h is an outdated and non-Standard header from Turbo C/C++ days, you should not be using it

+2

Everything is great, thank you ~ swim ~

+1

Namit Jain I see, thank you very much)

+1

Yes, everything is as you say) ~ swim ~

+1

Sin Cara M You're Welcome😅

+1

#include <stdio.h> int main() { int i; while(scanf("%d",&i)>0) { if(i==0) break; } printf("%d",i); return 0; }

0

I do not understand why, but it closes in me as soon as I enter the number, and wrote everything as Arsenic , ~ swim ~

-2

I don't think 'else if' is anything in C++ C++ has only if and else C has if/else if/else So according to me you will have to make nested conditions to make it work correctly...