+ 2

why cout<<n prints 0 when I input other than integers, supposed to show something else?

When I give input other than an integer i.e. char, string or any other it prints n as 0 why? #include <iostream> using namespace std; int main() { int n; cin>>n; cout<<n; return 0; }

28th Apr 2021, 6:14 PM
Shunon
Shunon - avatar
6 odpowiedzi
+ 5
🅰🅹 🅐🅝🅐🅝🅣 You may want to review and revise your answer. You can assign a char value to an int. int is a chars underlying type and implicit type conversion from char to int can occur. It just doesn't work directly as an input, but this will work fine; int x = 'x'; cout << x; Also, an uninitialized int is only set to 0 as a default when it is static or has global scope. This occurs pre-compile. A non-static int within a function will have a garbage value. Again, here it is the input creating the result of 0 for the mismatched type.
28th Apr 2021, 7:18 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
SuZu Because the type is Integer and you can not assign string or char value to integer. Also an integer has default value 0 so if you enter anything except integer then you will always get 0
28th Apr 2021, 6:33 PM
A͢J
A͢J - avatar
+ 2
You have to declare the variable n with the type of data you want to pass it, otherwise it will return 0. or handle exceptions so that it only denotes entering numbers
30th Apr 2021, 5:20 AM
Darién Domínguez Hernández
Darién Domínguez Hernández - avatar
28th Apr 2021, 6:37 PM
Shunon
Shunon - avatar
0
So If I have a code snippet taking n as an input and I want to show "input must be integers" every time user inputs non Integer value How I supposed to do that? 🅰🅹 🅐🅝🅐🅝🅣 **[nvm got it]**
28th Apr 2021, 6:40 PM
Shunon
Shunon - avatar
0
Alright thanks for explanation ChaoticDawg , yes I tried int x ='x'; cout<<x; it prints ascii value of character which is understandable
29th Apr 2021, 4:53 AM
Shunon
Shunon - avatar