while(guess!=ans1){
cout << "Enter your first guess: ";
cin >> guess;
}
This is the loop I am using but its not working can someone please tell me how I fix this?? (I am not using an ide btw.)
EDIT
Full code
#include <iostream>
using namespace std;
int main()
{
int ans1 = 3;
int ans2 = 7;
int ans3 = 12;
int guess;
while (guess != ans1)
{
cout << "Enter your first guess: ";
cin >> guess;
}
cout << "\nYou guessed correctly!";
while (guess != ans2)
{
cout << "Enter your second guess: ";
cin >> guess;
}
cout << "\nYou guessed correctly!";
while (guess != ans3)
{
cout << "Enter your final guess: ";
cin >> guess;
}
cout << "\nYou win!!!";
return 0;
}
>Solution :
I offer you some alternatives:
#include <iostream>
int main()
{
using std::cout; // this allows you to only use cout instead of std::cout
using std::cin; // and not import the entire namespace. Also, only within
// the main function. So no global pollution.
int const ans1 = 3; // these do not change, so they should be const
int const ans2 = 7;
int const ans3 = 12;
int guess = 0;
while (guess != ans1)
{
cout << "Enter your first guess: ";
cin >> guess;
}
cout << "\nYou guessed correctly!\n";
while (guess != ans2)
{
cout << "Enter your second guess: ";
cin >> guess;
}
cout << "\nYou guessed correctly!";
while (guess != ans3)
{
cout << "Enter your final guess: ";
cin >> guess;
}
cout << "\nYou win!!!";
}
But surely you notice we copied a lot of code. This is where we can make use of arrays. A lot of free tutorials will teach you C-style arrays, but this is the C++ way to do it:
#include <array>
#include <iostream>
int main()
{
using std::array;
using std::cout;
using std::cin;
// alternatively
array<int, 3> const answers = {3, 7, 12};
int guess = 0;
for( std::size_t i = 0; i < answers.size(); i++ ){ // (iterating loop, the "standard" for loop
while( guess != answers[i] ){
cout << "Enter your first guess: ";
cin >> guess;
}
cout << "\nYou guessed correctly!\n";
}
// alternatively
for( auto const& answer : answers ){ // range based loop (more complicated to understand)
while( guess != answers ){
cout << "Enter your first guess: ";
cin >> guess;
}
cout << "\nYou guessed correctly!\n";
}
return 0;
}