get and check input as while condition

This is a discussion on get and check input as while condition within the C++ Programming forums, part of the General Programming Boards category; How can I get and check the user input from within the condition of a while loop? For example, the ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    46

    get and check input as while condition

    How can I get and check the user input from within the condition of a while loop?
    For example, the Java equivalent would be

    Code:
    BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
    
    while (Integer.parseInt(new StringTokenizer(br.readLine()).nextToken()) != 999)
                   do something as long as input isn't 999
    the first line isn't important, but anyways, I just want to know how to test the input in the while loop condition.

    I tried
    Code:
    int a;
    while ((cin >> a) != 999)
    but that only tests the input stream, not the actual value of a.
    Is there another operation other than cin >> that I can use?

    Thanks.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,271
    Code:
    while ((cin >> a) && a != 999)
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    You'll have to call cin.clear() if the (cin >> a) part fails, as well as cin.ignore with a large value to ignore the bad characters input. You can search for examples. If you use the while exactly as laserlight showed, then both should be safe to call even if the a != 999 part is what fails.

  4. #4
    Registered User
    Join Date
    Feb 2005
    Posts
    46
    Right, thanks guys.

  5. #5
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    Just on a side note, you should check out java.util.Scanner

  6. #6
    Registered User
    Join Date
    Feb 2005
    Posts
    46
    Yeah, I'm still on 1.4 though.

  7. #7
    Registered User
    Join Date
    Apr 2006
    Posts
    2,053
    Quote Originally Posted by indigo0086
    Just on a side note, you should check out java.util.Scanner
    ??? how would the java scanner object help in a C++ program? This isn't a java board you know.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  8. #8
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    Quote Originally Posted by King Mir
    ??? how would the java scanner object help in a C++ program? This isn't a java board you know.
    keyword side note, as the question was already answered.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21