#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    3
    Rep Power
    0

    C++ use of getch?


    Hi everyone,

    I have made this programme using C++ only when I debug, it just flashes the answers at the end and doesnt hold them.. i know that I have to use getch but I cant work out where to put it!! Thanks :)


    #include<iostream>
    using namespace std;
    int main(void)
    { int sum=0,lessthan10=0;
    for(int i=1; i<11; ++i)
    { int input;
    cout<<endl<<"enter no. "<<i<<" ";
    cin>>input;
    sum+=input;
    if(input<10)
    lessthan10++;
    }
    cout<<endl<<endl
    <<"sum = "<<sum<<endl
    <<"average = "<<sum/10<<endl
    <<lessthan10<<" numbers are less than 10"
    <<endl;

    return 0;
    }
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    Your program runs in a Microsoft command console.
    Fix its behavior, don't corrupt your program.

    Refer to
    http://commandwindows.com/configure.htm or similar guide.

    Also, in my opinion as well as the view of program coverage, where you have
    Code:
    if(input<10) 
      lessthan10++;
    should be
    Code:
    lessthan10 += input < 10;
    It's simpler.

    Lastly, please test your program with the input
    0 1 1 1 1 1 1 1 1 1
    as in the command

    echo 0 1 1 1 1 1 1 1 1 1 | yourprogram

    Is the sum correct? The average?

    Finally lastly, I do most all of my shell work in an emacs shell buffer. It's permanent. I don't experience the problem you've crossed.
    Last edited by b49P23TIvg; December 4th, 2013 at 02:59 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    should be
    Code:

    lessthan10 += input < 10;

    It's simpler.
    That's a matter of opinion.

    There was nothing wrong with the code as written.

    What happens for example when the 1-line if statement (which you handily compressed) is suddenly no longer 1-line?

    You have to turn your clever trick back into a proper if statement.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo