Home > Enterprise >  Is cin.get() reading multiple digit characters at once?
Is cin.get() reading multiple digit characters at once?

Time:10-02

We were asked to write a simple C program by our teacher to add two numbers in the following format:

input: 12 14
output: m n = 26

The program must also work for other inputs in the form:

input: Hello please add 12 and 14 !
output: m n = 26

The solution that was given was:


    #include <iostream>
using namespace std;

int main(){
int m,n;
char ch;
while(cin.get(ch)){
if(isdigit(ch))
{
cin.putback(ch);
cin>>m;
break;
}
}
//cin.putback() restores the last character 

//read by cin.get() back to the input stream
while(cin.get(ch)){
if(isdigit(ch))
{
cin.putback(ch);
cin>>n;
break;
}
}
cin.ignore(80,'\n');
cout<<"m   n = "<<m n<<endl;
return 0;}

But now I need to know why this program also works for numbers that are not single digits. Shouldn't cin.get(char) just read one digit and cin.putback() return the same? Please help me I am a beginner.

CodePudding user response:

Yes, cin.get() will read only one character at a time.

The important part, where the number is actually read, is 4 lines below: cin>>m;. This will consume as many digits as possible and store the resulting integer in m.

Some more details:

// example with input 524 42

while(cin.get(ch))        // extract one character at a time
{                         // ch='5', remaining input="24 42"
    if(isdigit(ch))       // if it's a digit (0-9), then:
    {                         
        cin.putback(ch);  // Put it back into the stream, "unread" it
                          // remaining input="524 42"
        cin >> m;         // extract an integer from stream
                          // m=524, remaining input="42"    
        break;
    }
}

The reason for the loops seems to be to skip over any non-numeric input before a number appears. Note that there is a little bug here, since it will also ignore leading signs. (e.g. input -4 4 will output m n = 8)

  •  Tags:  
  • c io
  • Related