Validating input

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:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include <iostream>
#include <limits>
#include "DynamicProgramming.h"
using namespace 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.
I see, thank you. Sorry if this is the sort of thing that is basic, but I'm really lost with C++. Hopefully after this I won't be that lost.
Topic archived. No new replies allowed.