Reputation: 3
I am actually doing a homework problem and I have the program pretty much done. My only problem is when I enter a charactor or a number, it fails to reject it. Here is the problem:
Write a program to check for balancing symbols in the following languages:C++ (/* */, (), [], {}).
I have set up a list of if statements that makes sure if there is an uneven amount of symbols (/* */, (), [], {}) it will detect it. My only problem is when I enter a number it doesn't get filtered by any of my if statements (naturally) and it is passed through as a 'balanced' entry.
Back to my initial question, is there a way that i can have any 'int' detected and have it be rejected? Here is one of my attempts to kinda give an idea of what I am trying to do:
if (top == int)
{
cout << "Invalid Entry"; \\an integer is detected
main (); \\due to an int input it would rout back through to start
}
I am a total noob so any help or point in the right direction would be great
Upvotes: 0
Views: 282
Reputation: 43
There's many possible solutions, but one of my favorites is to call a function that will handle it for me.
bool IsInteger(string line) {
for (int i=0; i<line.size(); ++i) {
if (!isdigit(line[i])) {
return false;
}
}
return true;
}
int main() {
string input;
while (cin >> input) {
if (IsInteger(input)) {
cout << "Integer detected!" << endl;
} else {
// Do stuff
}
}
}
Upvotes: 0
Reputation: 1
You could check for valid integer inputs, and just reject these:
std::string input;
while(std::cin >> input) {
int dummy;
std::istringstream iss(input);
if(cin >> dummy) {
cout << "Invalid Entry" << endl; //an integer is detected
continue; // Read again
}
// ... process input
}
Upvotes: 3