Thread: while (cin>>x)

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    14

    Question while (cin>>x)

    Code:
     while (cin >> x) {
            ++count;
            sum += x ;
    }
    this is a C++ question, but i hope to find some help here.

    i'm reading "accelerated C++" book and they have this example to demo that cin can be used to count previously entered values.
    why cin holds all the previously entered values? would not it be a risk? if i have some system sending high frequency signals to CIN and then i'd count their number.... Sounds dangerous to me...

    what am i not understanding here?

    Thank you

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    what am i not understanding here?
    That this is a C++ question, so it should have been posted to the C++ forum?

    Other than that you don't seem to understand that cin stands for Console INput. The console doesn't actually hold the previous values, it captures the keyboard input and inserts that input into program variables.

    Jim

  3. #3
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    You are right, in the sense that the person handling the input decides whether your program halts.
    If you do not want that, do something like:
    Code:
    int n = 10;
    while ((std::cin >> x) && n--) {
      //...
    }

  4. #4
    Registered User
    Join Date
    Sep 2015
    Posts
    14
    Quote Originally Posted by manasij7479 View Post
    You are right, in the sense that the person handling the input decides whether your program halts.
    If you do not want that, do something like:
    Code:
    int n = 10;
    while ((std::cin >> x) && n--) {
      //...
    }
    thank you . Sorry about C++ in C forum.

Popular pages Recent additions subscribe to a feed

Tags for this Thread