Link to home
Start Free TrialLog in
Avatar of William39
William39

asked on

Compiling source code in C++ using Dev-C++ program

Experts, I am new to programming and have been trying to get this program to work but have been unable to get it to compile or build. I want it to display the following:
                              Welcome to the game!
                              Please guess the secret number: user input
Then when user inputs number to display as determined by the input number:
                             Wrong number, too small (or too big depended on inputed number)
                             Please guess the secret number:
At this point allow the user to try again with the same results
                              Wrong number, too big (or too small depended on inputed number)
                              Please guess the secret number:
or if the number is correctly guess to display this message
                             Congratulations! You figured out the secret number.
at this point the game would end. Here is the code that I have written can someone please tell me what I have done wrong with the code itself.

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    // C++ code starts here
   std::cout << "Welcome to the game!"<< std::endl;
   std::cout <<"Please guess the secret number";
   cin >>number
         if (number = 88)
   {
      std::cout <<"Congratuations! You figured out the secret number."<< std::endl;
   }
   else if ( grade < 88 )
   {
      std::cout <<"Wrong number, too small."<< std::endl;
      std::cout <<"Please guess the secret number.";
      cin >> number
   }
   else if ( grade > 88 )
   {
      std::cout <<"Wrong number, too big."<< std::endl;
      std::cout <<"Please guess the secret number";
      cin >>number
   }
}
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    system("PAUSE");
    return 0;

Avatar of SeanDurkin
SeanDurkin
Flag of United States of America image

A couple things:

You didn't declare number. In C++, you have to declare variables before you can use them (unlike language like PHP). Just add an int number; to your code.

In this line:

>> cin >>number

You forgot a semicolon, and you missed it in some other places, too. Check your compiler's errors, it tells you that you need semicolons when you forget them.

>> if (number = 88)

You are using the assignment operator (=) instead of what you want, the equality operator (==). The assignment operator will assign 88 to number every time it enters the if condition, so it will always be true. You want to check if number is equal to 88, so you use (==).

>> else if ( grade < 88 )

Where did you get "grade" from? Did you mean to use number? Also, these two statements:

>> system("PAUSE");
>> return 0;

Are outside of main(). This is probably just a small mistake on your part (misplacing main()'s end bracket); just stick them back in main().

Go ahead and fix all these errors before we address any more problems.
Here are the changes necessary to get it to compile.  The problems fell into
1)  Not defining a variable before using it -- int number, for example
2)  Omitted semicolons.  It looks as though you forgot the semicolon on "cin >>number" and then cut-and-pasted the erroneous line a few times.
3)  Using the wrong variable name (grade) instead of the variable you read into (number).
4)  Final closing brace was not the final thing in the source
I've added comments showing what changes were necessary.

I also noticed that
   if (number = 88)
is an assignment.  This is a very common mistake, and should be
   if (number == 88)
Even better is to write
   if (88 == number)
because comparison, not assignment, is what you intend, and the erroneous
   if (88 = number)
will not compile.

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    // C++ code starts here
   std::cout << "Welcome to the game!"<< std::endl;
   std::cout <<"Please guess the secret number";
   int number;  // << define number
   cin >>number; // << added semicolon
         if (number == 88) // << changed assignment to comparison
   {
      std::cout <<"Congratuations! You figured out the secret number."<< std::endl;
   }
   else if ( number/*grade*/ < 88 ) // << changed grade to number
   {
      std::cout <<"Wrong number, too small."<< std::endl;
      std::cout <<"Please guess the secret number.";
      cin >> number; // << added semicolon
   }
   else if ( number/*grade*/ > 88 ) // << changed grade to number
   {
      std::cout <<"Wrong number, too big."<< std::endl;
      std::cout <<"Please guess the secret number";
      cin >>number; // << added semicolon
   }
// << moved closing brace from here
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    system("PAUSE");
    return 0;
} // << moved down here from above
Sorry, Sean, was working on this when you posted.
Avatar of William39
William39

ASKER

Sean and josgood,
Thank you both so much after changing the items you both mentioned everything compiled and ran. Now can you tell me or show me how to make the program finish out the rest of the game. When I ran this it only gave me the one chance to make a guess. I am thinking that I have to put a loop statement or arrange the if statement differently or am I on the wrong track.
I suggest a
   bool answeredCorrectly = false;
   while (!answeredCorrectly) {
as your loop control.  The loop obviously will need to include the 'if' and both 'else' clauses.

answeredCorrectly gets set, of course, when the question is answered correctly.

It seems best to ask
   std::cout <<"Please guess the secret number";
as the first statement of the loop.

This implies removing the
         std::cout <<"Please guess the secret number.";
         cin >> number; // << added semicolon
in each of the else clauses, since the question is asked at the top of the loop
And I recommend you perform error checking for your program. For example, if you put in the while loop and instead of entering a number you enter a letter, it will go into an infinite loop. To fix this, you can replace all statements like:

cin >> number;

with the following:

while(!(cin >> number))
{
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

This code waits until the user enters a valid integer for number. If the value entered is not valid (i.e. can be converted to type int), then the input stream enters an error state and returns false (without clearing the stream). So, you have to manually do it. The clear() function clears the error state, and the ignore() function gets rid of any junk still left in the stream. It will remove all characters up to (and including) the newline character ('\n'). The reason it would loop infinitely without this is that once the input stream enters the error state it will look at all other cin >> number; statements and fail them, so the value of number would never change.
NOt sure I am clear on what you are tell me here, If I am understanding you are saying to remove all of the cin >> number: sections and replacing them with the full section you give:
while(!(cin >> number))
{
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
also removing removing the:
std::cout <<"Please guess the secret number.";
these are to be removed from the else if sections only correct?
Not sure where I should insert the:
bool answeredCorrectly = false;
   while (!answeredCorrectly) {
statement nor how many times I shold enter this section. Been looking all of this information up but none of the examples I am seeing is making any sense to me.
Right, but josgood was saying instead of having that statement and the input (cin) statement three times, just put it once at the top of all the if statements. So you have:

// this is all inside the while loop

std::cout <<"Please guess the secret number.";

while(!(cin >> number))
{
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

if(number == 88)
{
      /* tell him he got it right */

      /* now exit */
      return;
}
else if(number > 88)
{
      /* tell him he's wrong */
}
else
{
      /* tell him he's wrong */
}
See my above post, everything is inside the while loop (except for system("PAUSE") and return 0). The idea is that it continues until the user has guessed the correct number. When he guesses it you can either put a statement inside the first if() such as:

return 0;

or:

break;

The break statement will exit the innermost while or for loop (or switch statement) that it appears in. In this case, it would exit out of the while (!answeredCorrectly) loop. If you do that, you don' t need an answeredCorrectly boolean variable. Of course, if it's easier for you to do, you can just keep that in there, and instead just do this when the user guesses the correct value:

answeredCorrectly = true;

Then it will exit the while loop when it comes back around (after all the if stuff) and tries to execute the while condition again.
So the code would look like this then if I follow everything correctly:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    // C++ code starts here

std::cout <<"Please guess the secret number.";

while(!(cin >> number))
{
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

if(number == 88)
{
      /* tell him he got it right */
std::cout <<"Congratuations! You figured out the secret number."<< std::endl;
      /* now exit */
      return;
}
else if(number > 88)
{
      /* tell him he's wrong */
std::cout <<"Wrong number, too big."<< std::endl;
}
else if(number < 88)
{
      /* tell him he's wrong */
std::cout <<"Wrong number, too small."<< std::endl;
}
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    system("PAUSE");
    return 0;
}
ASKER CERTIFIED SOLUTION
Avatar of SeanDurkin
SeanDurkin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It will loop infinitely (because true is always true) so the only way you can exit the program is by guessing the correct number. Of course, as I said before, instead of putting:

>> system("PAUSE");
>> return 0;

inside if(number == 88) { ... } you can just put:

break;

and it will exit the while loop, and exit normally at the bottom. It just involves less code, but either way works.
Ok still having problems with this set up it will not compile again here is what I have now. Not sure what I did wrong with what you have giving me on this, it has to be a typo or something on my part. Can you still help?
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    // C++ code starts here
std::cout <<"Please guess the secret number.";
while(!(cin >> number))
{
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if(number == 88)
{
      /* tell him he got it right */
std::cout <<"Congratuations! You figured out the secret number."<< std::endl;
break;
}
else if(number > 88)
{
      /* tell him he's wrong */
std::cout <<"Wrong number, too big."<< std::endl;
}
else if(number < 88)
{
      /* tell him he's wrong */
std::cout <<"Wrong number, too small."<< std::endl;
}
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    system("PAUSE");
    return 0;
}

It is giving me the following errors in the compile log:
Compiler: Default compiler
\CPP_Programs\Week 2 V 7.cpp" CPP_Programs\Week 2 V 7.exe"   -fexceptions -g3  -I"C:\Dev-Cpp\include\c++"  -I"C:\Dev-Cpp\include\c++\mingw32"  -I"C:\Dev-Cpp\include\c++\backward"  -I"C:\Dev-Cpp\include"   -L"C:\Dev-Cpp\lib"
CPP_Programs/Week 2 V 7.cpp: In function `int main(int, char**)':
CPP_Programs/Week 2 V 7.cpp:15: `number' undeclared (first use this function)
CPP_Programs/Week 2 V 7.cpp:15: (Each undeclared identifier is reported only once for each function it appears in.)
CPP_Programs/Week 2 V 7.cpp:24: break
   statement not within loop or switch
Execution terminated
You still don't have a while loop like the code I posted above does; look at line 9 in the above code.
Sean,
Got your code and it is doing the same thing when I compile it with line 18 and won't compile. At least it is only three errors with your layout. The complier errors are:

CPP_Programs\Week 2 V 7.exe"   -fexceptions -g3  -I"C:\Dev-Cpp\include\c++"  -I"C:\Dev-Cpp\include\c++\mingw32"  -I"C:\Dev-Cpp\include\c++\backward"  -I"C:\Dev-Cpp\include"   -L"C:\Dev-Cpp\lib"
CPP_Programs/Week 2 V 7.cpp: In function `int main(int, char**)':
CPP_Programs/Week 2 V 7.cpp:18: `number' undeclared (first use this function)
CPP_Programs/Week 2 V 7.cpp:18: (Each undeclared identifier is reported only once for each function it appears in.)

Execution terminated
Oh sorry, I didn't try to compile before I posted. You still haven't fixed the declaration of number. As I said before, it won't recognize a variable unless you declare it:

int number;
Ok have fixed that problem but it still only allows one try at the number and then shuts down. I used your code and included the int number line what else can I do?
post the code that you used
also please use the "Attach Code Snippet" feature for posting your code, and indent it so it's easier to read
Here is everything as it is written for the compiler, for some reason that I don't understand it is not looping and no matter what number is inputted by the user the same message appears "Wrong number, too small:Press any key to continue..." When you press any key the whole program shuts down.

 
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
 
int main(int nNumberofArgs, char* pszArgs[])
{
	// C++ code starts here
    int number;
    while(true)
	{
		std::cout <<"Welcome to the game.";
        std::cout <<"Please guess the secret number.";
		
		while(!(cin >> number))
		{
		      cin.clear();
		      cin.ignore(numeric_limits<streamsize>::max(), '\n');
		}
		
		if(number == 88)
		{
		      /* tell him he got it right */
			std::cout <<"Congratuations! You figured out the secret number."<< std::endl;
			
		      /* now exit */
		      system("PAUSE");
		      return 0;
		}
		else if(number > 88)
		{
			/* tell him he's wrong */
			std::cout <<"Wrong number, too big."<< std::endl;
		}
		else if(number < 88)
		{
			/* tell him he's wrong */
			std::cout <<"Wrong number, too small."<< std::endl;
		}
	}
	
	// wait until user is ready before terminating program
	// to allow the user to see the program results
	system("PAUSE");
	return 0;
} 
 

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> no matter what number is inputted by the user the same message appears "Wrong number, too small:Press any
>> key to continue..."

I don't mean to deny what you're saying, but it seems, with that code, that the output you said you're seeing is impossible. There is no apparent way to break out of the while(true) loop, because it is not provided in the code. If the number given was too low, it should output "Wrong number, too small." Then it should continue the loop. Even if the stream were corrupted somehow it still would not exit the while(true) loop unless there was some kind of break statement in there, and the only way to exit from inside the while(true) loop is if number indeed does equal 88, in which case it would print: "Congratuations! You figured out the secret number." before exiting.

Again, I apologize for doubting you, but could you double-check that you're compiling the code that you've attached to your post? I'm also using the Dev-C++ IDE to compile your program, and it's working fine for me as well. If the problem persists, can you reattach the code you are using (just do ctrl-a and then ctrl-c to copy all the text from your .cpp file in Dev-C++) as well as the exact output of your program (including the welcome messages - exactly how it's formatted on the console)?

On a side note, you may want to stick the:

>> std::cout <<"Welcome to the game.";

before the while(true) loop, because otherwise it welcomes you every time you guess a number.
Here is the code and the attached file is a screen capture of the program when I run it and input the number which should come up with a different answer. I did change the section that you said to change in your last post "On a side note, you may want to stick the:
>> std::cout <<"Welcome to the game.";
before the while(true) loop, because otherwise it welcomes you every time you guess a number."
As for the suggestion from josgood of adding the code
" had to add
   #include <limits>
and then it ran perfectly for me."
Where would this code be added at and what does it do? I have not seen this used anywhere else so far.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
 
int main(int nNumberofArgs, char* pszArgs[])
{
	// C++ code starts here
    int number;
    std::cout <<"Welcome to the game.";
    while(true)
	{
        std::cout <<"Please guess the secret number.";
		
		while(!(cin >> number))
		{
		      cin.clear();
		      cin.ignore(numeric_limits<streamsize>::max(), '\n');
		}
		
		if(number == 88)
		{
		      /* tell him he got it right */
			std::cout <<"Congratuations! You figured out the secret number."<< std::endl;
			
		      /* now exit */
		      system("PAUSE");
		      return 0;
		}
		else if(number > 88)
		{
			/* tell him he's wrong */
			std::cout <<"Wrong number, too big."<< std::endl;
		}
		else if(number < 88)
		{
			/* tell him he's wrong */
			std::cout <<"Wrong number, too small."<< std::endl;
		}
	}
	
	// wait until user is ready before terminating program
	// to allow the user to see the program results
	system("PAUSE");
	return 0;
} 
 

Open in new window

Capture.GIF
iosgood, I don't know what I was thinking when I said I didn't know where to include the "#include <limits>" code. I have not had a good day, even after adding that section and saving as a different version it stills does the same thing. Everything inputted it comes back with the saying that Number to big section. Could it be the program "Dev-C++" itself is messing up. I have version 4.9.8.0 presently, it came with the book I bought to try and learn this stuff.
No, that seems like a fairly up-to-date version of Dev-C++. This still doesn't make any sense. Have you tried making a new project and putting the source code in a new .cpp file?
I will try that I will go line by line if that is what it takes.
Ok I don't know why that worked but it did, can you explain that? All I did was copy the file from my last post and put it into a new file saved it and bamm it works as needed. Thanks to the both of you now I just need to figure out how to award the points. looking back it seems that SeanDurkin made the most contributions but I don't want to exclude iosgood out. Both of you have worked in helping me actully you both did most of the work. Would 300 to SeanDurkin and iosgood 200 be fair?
It could be that somehow the project file was corrupted, but I have a strange suspicion that you were just saving the .cpp file instead of compiling it. :) I could be wrong, though; it seemed like a very strange problem and it probably could have happened for a number of different reasons, all of which are unknown to me. :) Anyway, it doesn't matter to me how you split the points, I'm just glad we got it fixed!

Best of luck,
Sean
I appreciate the gesture, but josgood did help you, so you have to award him some of the points. To reopen the question, you can post in the General Community Support zone {https://www.experts-exchange.com/Community_Support/General/} and ask a moderator to reassign the points. Just specify which answer IDs you want accepted (for example you originally accepted mine, ID:21547904) and how many points for each.

Thanks again! :)
Sean, you are truly a gentleman!
Joe
thanks! :)
SeanDurkin,
I decided to award all of the points to you because of the sheer amount of work you put into this for me and making me understand a little bit better than I did before starting all of this.
Thank you all, sorry it has taken me so long to get back to this question. Internet has been down here in Iraq where I am at.