1

So this is the code

#include<iostream>

using namespace std;
int main(){
    int a,b;
    while(true){
        cout<<"Enter the value of a and b ";
        cin>>a>>b;
        if(a=='|'||b=='|')
            break;
        else
            cout<<"The value of a is "<<a<<"\nThe value of b is "<<b<<endl;
    }
}

and the question is Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.

When i enter input like | it prints infinitely "The value of a is and value of b is ". What is the reason for this?enter code here

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • `a` and `b` are integers, `|` is not an integer. – Barmar Dec 18 '16 at 18:09
  • Never use same variables to possibly store 2 diffrent data types. Is this some kind of homework? Really bad to make you do it that way. If you expect both characters and number I would go with `std::string` and check whether a user has input a number (and then change a string input to int) or a character (then check if the character is `|`) – Fureeish Dec 18 '16 at 18:09
  • The value of `'|'` is its character code. 124 in ASCII. So your program will exit when you type `124`. – Barmar Dec 18 '16 at 18:10
  • @Barmar this was not the question. The task, I believe, was to terminate the program when `|` is entered. User is expected to input exactly `|`, not the value of that character in ASCII – Fureeish Dec 18 '16 at 18:12
  • @Fureeish I know, I was just telling him how his program actually works. – Barmar Dec 18 '16 at 18:13
  • @Barmar I would disagree now. You just told him what is the ASCII code of `|` character. You neither explained why the loop goes infinite nor why when entering a `|` character the ASCII value of it is not given to `int` by `cin`. – Fureeish Dec 18 '16 at 18:15

2 Answers2

0

Your istream operator >> as_int is failing and really doing nothing so your loop just keeps going. Either input as chars and convert to ints with checks, or or check the stream for errors.

cin>>a>>b;
if( cin.fail( ) )
    break;

istream reading after failure

Additionally: If you had have traced into the istream operator you would have seen why it was not blocking, that it had failed. Always trace when something is wrong...

Community
  • 1
  • 1
lakeweb
  • 1,859
  • 2
  • 16
  • 21
0

std::cin (and I think all streams) by default will set an error flag when you try to read into an invalid data type (e.g. here with trying to read a char into an int variable) and that flag will prevent other std::cin to run until the flag is cleared. To rest the stream, use std::cin.clear() to the reset the error flag and then you have to remove the bad input, either through std::cin.ignore() or read into a string buffer or something, from the stream as it will still be there.

Lawrence
  • 862
  • 1
  • 7
  • 15