Hope you are doing well. I am a begineer in C++ and this is my first post here.
I wrote a code where the user is asked to enter their name. If the name contains a digit then it should give an error and ask user to enter name again. The issue is that when I enter a string it still keeps asking to enter the name. It is not able to exit the while loop. I change the 'result' bool to 'true' in the end if the name entered is a string but the while loop still thinks that 'result' is false so it does not exit the while loop. Not sure why that is happening. Any help is appreciated. Thanks!
using namespace std;
int main()
{
string name;
bool result = false;
while(result == false){
cout << "What's your name?" << endl;
cin >> name;
for(int i = 0; i < name.length(); i++){
if(isdigit(name[i])){
cout << "Invalid input! Please enter only letters." << endl;
break;
}
}
bool result = true;
}
}
You're creating a new inner variable with the same name (result) and set it to true but it is not used anywhere. The while loop is 'listening' to the outer variable result which is not changed. Creating a new inner variable with the same name is commonly called 'shadowing'. See:
When you remove the type bool in front of the the expression the outer variable is not shadowed anymore. Then you have the problem that result will be set to true regardless and the loop will end immediately. See dutch code for how to solvve that.
One question about this line in your code:
for (bool result = false; !result; )
Is '!result' same as 'result==false' ? i.e. if we replace it in the above line, will it work the same?
I am a bit confused by this because I am thinking that !result means NOTresult. So if result=true, then !result=false; but if result=false, then !result=true. So the value of !result will change depending of its initial value. Is that correct?
Thank you @coder777. I did not know about the concept of 'shadowing'. I had put the inner variable (bool result = true;) precisely to use it as a condition to exit the while loop and thought that the while loop will listen to this new value since it was inside the while loop.
But now I understand why it was not exiting, because as soon as the while loop ended, the inner variable was destroyed and now it again using the outer variable which was still set to 'false'.
Just a follow-up question. If we create a variable just before starting a loop and we want to change this variable value not just within the loop statement but also in the recurring loop runs, how could we do it? Or how to change the outer variable value.
Thank you, @seeplus. Yes, that is a good point. That way (with isalpha) it will strictly check that the entered keys are only alphabets vs (with isdigit) only checking that the entered keys are not digits.