#include <iostream>
usingnamespace std;
int main()
{
int a = 0;
int i = 1 ;
while ( a != i )
{
cout << "Enter any number other than " << i -1 << endl;
cin >> a;
cout << "you entered!" <<a<< endl;
if(a == i -1)
{
a = i;
}
else
{
i++;
a = 0;
}
}
cout << "you're not supposed" << endl;
return 0;
}
#include <iostream>
//use std:: instead of using namespace std; - Google it
int main()
{
int a = 0;
bool flag = true; // you can use a boolean to determine when the loop should end so you dont have to use i-1 and make things clunky.
int i = 0; // Because of bool we can initialize it to 0
while (flag) // runs as long as flag equals true
{
std::cout << "Enter any number other than " << i << std::endl;
std::cin >> a;
std::cout << "you entered!" <<a<< std::endl;
if(a == i )
{
flag = false; // sets flag to false, which ends the loop
}
else
{
i++;
// the a = 0; you had here doesnt do anything, the user will just overwrite it no matter what
}
}
std::cout << "you're not supposed" << std::endl;
return 0;
}
This is a good case for a do-while loop instead. Use do/while when the loop is guaranteed to execute at least once. Below I've changed your original code to a do/while, but it would probably be best to combine the do/while with TarikNeaj's idea of a flag.
Also, as an alternative to TarikNeaj's suggestion, add using statements for each name that you indent to use:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int a = 0;
int i = 1 ;
do
{
cout << "Enter any number other than " << i -1 << endl;
cin >> a;
cout << "you entered!" <<a<< endl;
if(a == i -1)
{
a = i;
}
else
{
i++;
a = 0;
}
} while (a != i);
cout << "you're not supposed" << endl;
return 0;
}
@dhayden in my opinion using your alternative is fine, but it can get real messy later on. Especially when you are using libraries, and you'll have many more extra usings, and you need them in like most files, etc etc. Just gets real messy.
For example when using SFML. You'll need tens of different usings. It's much better in my opinion to get used to writing std:: or sf::, you get used to it real quick and it would become second nature.