2

why it always gives zero output?

 2 years ago
source link: https://www.codesd.com/item/why-it-always-gives-zero-output.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

why it always gives zero output?

advertisements
int i;
cin>>i;
cout<<i

when we entered Character i.e 'A' why it gives Zero output ?


Because A is not a numeric value suitable for storing in an integer, so it will leave your integer alone, as shown here:

#include <iostream>
int main (void) {
    int i = 12345;
    std::cin >> i;
    std::cout << i << std::endl;
    return 0;
}

When you run that code and enter A, it outputs 12345 as the value doesn't change.

If you want truly robust input, it's usually better to input lines as strings then convert them yourself.

"Mickey-mouse" programs or those where you have total control over the input can use the sort of input methods you're using, serious code should use more suitable methods.


If your intent is to convert an input character into its integer code, you can use something like:

#include <iostream>
int main (void) {
    char c;
    std::cin >> c;
    std::cout << (int)c << std::endl;
    return 0;
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK