I want to write a small "calculator" that can handle wrong input of int. In order to implement that, I used a function that checks the input using a while-loop. It works properly, if I add the loop directly into my int main function. But when I'm using my input_nr function, it does'nt return the new value of the integer (here, for instance a). My value of a is always the initilized one in the int main() function.
I think something in my loop is wrong or missing that properly returns my new input for a.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <math.h>
#include <fstream>
#include "square.h"
usingnamespace std;
int input_nr(int x)
{
int y = 0; //I added the new int y, because I thought the loop can't re-initilize "x"
x = y; //set my input to y = 0;
while (cin) {
cin >> y; //input new value of y
if (!cin || y > 10 || y < 1){
cout << "No proper Input."; cin.clear(); cin.ignore();
cout << "\nRepeat input of integer: "; //this works ok
}
else
{
x=y; //set x to y
break;
}
}
return (x); // I think something went wrong here. It also does'nt work;
//when I just write "return (x+5)" or so, for example
};
int main()
{
int a = 1; //i have to initialize my variable
//before using it in a function
int b;
char o;
cout << "Enter two integers (between 1 and 10) and an operator.\n";
while (cin)
{
cout << "\nFirst integer (1-10): "; input_nr(a);
// If i am using the while-statement of my input_nr function here directly,
//everything goes well
cout << "\na = " << a;
// it always outputs the initialized value of a, so 1 and not the new
//value from the input_nr function
}
//end of program
cout << endl;
cin.get();
return 0;
}
#include <iostream>
int input_nr()
{
bool keep_going = true;
int y = 0;
do
{
std::cin >> y;
if (!std::cin.good() || y > 10 || y < 1)
{
std::cout << "No proper Input.";
std::cin.clear();
std::cin.ignore();
std::cout << "\nRepeat input of integer: ";
keep_going = true;
}
else
keep_going = false;
}
while (keep_going == true);
return y;
}
int main()
{
int a = 1;
int counter = 0;
std::cout << "Enter two integers (between 1 and 10) and an operator.\n";
while(counter < 2)
{
std::cout << counter << " Integer (1-10): ";
a = input_nr();
std::cout << "a = " << a << '\n';
counter++;
}
return 0;
}
An alternative way.
ignore clears the cin buffer where it still contains erroneous data. eg if a character is entered or other non-integer 'stuff'
Enter two integers (between 1 and 10) and an operator.
0 Integer (1-10): 2
a = 2
1 Integer (1-10): 0
No proper Input.
Repeat input of integer: 9
a = 9
Program ended with exit code: 0