Hey Guys. I trying to create a simple loop but for some reason when it compiles something strange happens. Basically I want to make a while loop that prints and allows you to re'input' a value until it is both an integer and not below 1. Here is my code:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <cctype>
usingnamespace std;
using std::string;
int enterStartingPopulation (int startingPopulation)
{
cout << "Enter the starting population: ";
while ((! (cin >> startingPopulation))||(startingPopulation < 1))
{
cin.clear();
cin.ignore();
cout << "Invalid Input. Enter a positive integer: ";
cin >> startingPopulation;
}
return (startingPopulation);
}
int main ()
{
int startingPopulation = enterStartingPopulation (startingPopulation);
return (0);
}
and here is the output:
1 2 3 4 5 6 7 8
Enter the starting population: -7
Invalid Input. Enter a positive interger: -5
-8
Invalid Input. Enter a positive interger: -4
-6
Invalid Input. Enter a positive interger: s
Invalid Input. Enter a positive interger: g
Invalid Input. Enter a positive interger: h
As you can see it works fine when you don't enter a integer and it justs keeps on printing "Invalid Input..." until you do, but when you enter a negative number, it only prints something every other negative number. Hard to put into words but the example above shows it clearly. Any help would be much appreciated. Thanks in advance!
In line 21. you call "cin >> startingPopulation;", while it is already called every time while-loop enters line 16., so the application asks you another time to write number (twice), while only the second one counts.
That works! Thank you very much. Forgot that I was actually calling "cin >> startingPopulation;" every time the loop repeated. Thank you very much for your help! :)