I need help validating user input. My code has two instances of input validation, one for integers and another for chars, the issue is that I can't seem to get it to work properly and I believe it is because I'm attempting to do it the same way I would in java. Here's what I've got:
#include <iostream>
#include <limits>
#include "DynamicProgramming.h"
usingnamespace std;
int main() {
bool continueProgram = true;
char answer;
int input;
int result;
DynamicProgramming* dpobject = new DynamicProgramming;
while (continueProgram){
cout << "Choose a value to calculate: " << endl;
while(!(cin >> input)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max());
cout << "This is not a number, please try again: ";
}
result = dpobject->Fibonacci(input);
cout << "The result is: " + result << endl;
I'd also like to know what endl is for, I'm not sure if I'm using it right.
cin.ignore(numeric_limits<streamsize>::max());
You are ignoring all characters untill the end of the stream (read: all characters you entered or enter in future). YOu probably want to ignore everything until newline: cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "The result is: " + result << endl;You are adding pointers here. You want to replace + with <<.
<< std::endl is actually << '\n' << std::flush;. So you are sending endline symbol and forcibly flushing stream buffer. Usually there is no reason to do that, so I just newline symbol where it needed.