Shaswat Tripathi
Shaswat Tripathi

Reputation: 13

Why is the following code not throwing an error?

When I input 123456,the following code generates 1 2 3 4 5 6 But since digits can only hold a single digit value, shouldn't this code throw an error?

#include <iostream>

using namespace std;

int main()
{
    char digit;
    cout << "Enter a six-digit number: ";
    for (int p = 1; p <= 6; p++) {
        cin>>digit;
        cout<<digit<<" ";
    }

    return 0;
}

Upvotes: 1

Views: 195

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

The first time through, cin doesn't "know" that you have not yet stored a value in digits (you may as well have, despite the lack of initialiser).

It does not know this the second or third or fourth or fifth or sixth time, either.

It just replaces what's already there with what it reads from the stream.

This is normal, expected behaviour and not a cause for error.

By the end of your program, digits contains the ASCII code (probably) of the character '6'. Just that one character. You're seeing multiple values output because you output each value individually in a loop.

Upvotes: 2

t.niese
t.niese

Reputation: 40842

With cin>>digit you request one char from the cin stream.

std::cin is of the type istream which is basic_istream<char>, so it is basically a buffer of char.

And because of that cin>>digit will always be valid and removes one char from the stream and saves it in the digit as long as the input stream is in a valid state, and has data available.

Upvotes: 4

Related Questions