+ 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; }
6 Antworten
+ 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.
+ 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
+ 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
+ 1
Ohh ok Thanks 🅰🅹 🅐🅝🅐🅝🅣
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]**
0
Alright thanks for explanation ChaoticDawg , yes I tried int x ='x';
cout<<x; it prints ascii value of character which is understandable