Initially, I was trying to write a program to ask the user to enter only a negative integer value and until entered, it will be calling itself in a recursive way. Like:
#include <iostream>
using namespace std;
void printNegativeNum () {
int neg_no;
cout << "Enter a negative number: " << endl;
cin >> neg_no;
if (neg_no >= 0){
cout << "Please enter only negative number." << endl;
printNegativeNum();
}
cout << neg_no;
}
int main(){
printNegativeNum();
return 0;
}
This code on being given char input was entering infinite loop, leading to segmentation fault.
Then, I studied about dealing with this and found few solutions for while loop and tried to do the in above recursive function.
#include <iostream>
using namespace std;
void printNegativeNum () {
int neg_no;
cout << "Enter a negative number: " << endl;
if(cin >> neg_no) {
if (neg_no >= 0){
cout << "Please enter only negative number." << endl;
printNegativeNum();
}
}
cout << neg_no << " ";
}
int main(){
printNegativeNum();
return 0;
}
This thing worked and no more entering the infinite loop. But, now all the previous integer values entered before the char value which leads to program termination, getting printed as if the
court << neg_no << " ";
is getting executed and it was carrying all the values entered before the char constant.
I am unable to understand how?
I in trail and error used cin.clear() before the cout statement. But, that too was in vain.
Please Help.