Friday, July 31, 2009

C++ program won't work..?

Just in case.. It compiles just fine


*There Is No Error Message*











So basically, I have written this code that


will let a user choose 2 numbers.


the program will either


1: Tell the user all of the odd numbers between the first number


and second.


or


2: Write the odd numbers to a file, "odds.txt".





This can be found at


http://seklym4.t35.com/odds.txt





I can't find out what could be wrong with it, but there definately


*is* something.





I use Bloodshed Dev-C++, just in case my code won't


compile in your compiler.





Please, could you revise the code, and post it, or at least just


tell me what I need to change to make it work.





Any help would be greatly appreciated.

C++ program won't work..?
Sent an email with the fixed code.





Your problem was with your if conditions.


Noticed that nothing was being written.


Program wasn't getting to the part with cout%26lt;%26lt;"Done!";





I check to see if start == end or end %26lt; start.


I take mod 2 to see if the number starts out even or odd.





Probably should've added comments to the code but heh...
Reply:With your code


You are using the bit AND operator.


To detect odd numbers


(number %26amp; 1) will be 1 if the number is odd and 0 if even number





To revise your code, optimized and removed unnecessary goto statements.





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;





using namespace std;





int main()


{


ofstream oddfile("odds.txt");//To make file odds.txt


int start;


int end;


string yesno;


cout%26lt;%26lt;"I will tell you the odd numbers from..\n";


cout%26lt;%26lt;"This number: ";


cin%26gt;%26gt; start;


cout%26lt;%26lt;"To this one: ";


cin%26gt;%26gt; end;





cout%26lt;%26lt;"\n\n And..\nWould you like to write the odd numbers to a file?\n";


cin%26gt;%26gt; yesno;


getline( cin, yesno, '\n' );


if ( yesno == "yes")


{


if ((start %26amp; 1) == 0)


start++;


if (start %26lt;= end)


{


for (int i = start; i %26lt;= end; i += 2)


oddfile%26lt;%26lt; start%26lt;%26lt;endl;


cout%26lt;%26lt;"Done!";


oddfile.close();


}


else {


cout%26lt;%26lt;"That's an invalid function.. Thanks for playing though";


oddfile.close();


}


}


else if ( yesno == "no" || "n"){


if ((start %26amp; 1) == 0)


start++;


if (start %26lt;= end)


{


for (int i = start; i %26lt;= end; i += 2)


cout%26lt;%26lt; start%26lt;%26lt;',';


cout%26lt;%26lt;endl%26lt;%26lt;"Done!";


}


else {


cout%26lt;%26lt;"That's an invalid function.. Thanks for playing though";


}


}


else{


cout%26lt;%26lt;"That's an invalid function.. Thanks for playing though";


}


system("pause");


}

flamingo plant

No comments:

Post a Comment