Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of threads: 5430
Number of posts: 16951

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Why does it do what it does Posted by pyler on 14 May 2011 at 6:02 PM
If you run this code and type in 1/5 upon the prompt
the program outputs the same values for the remaining trials instead of prompting for another value
Why does it do this?

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
double n, gal,liters;
    for(n=0;n<=9;n++){
        cout<<"Enter amount of gallons: ";
        cin>>gal;
        liters = gal*3.785;
        cout<<gal<<" gallons in liters is "<<liters<<"\n\n";}

return 0;}

Report
Re: Why does it do what it does Posted by pseudocoder on 14 May 2011 at 11:37 PM
if you're actually entering 1/5, cin >> gal will go into a fail state upon reading the / as gal is a double and / is not. you might try adding something like below to give it a quick check.

... bits of code
cin >> gal;

if(cin.fail()) {
   // take some action;
}

... bits of code




 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.