I'm using an if (!cin) expression to test whether user input a character or a number, but I want to let the '#' character through, as I want using that character to cause the loop to break.
That sounds like a good idea, but I need the input to be integers as it is processed further. In another function it is used for finding an average etc.
If you tell cin to expect an integer ( std::cin >> ar[i]; ), and you feed it '#' , then cin will fail. You cannot tell it to expect an int value and then feed it something that is not an int.
Fetch input to a string.
Look at the string.
If the string is a number, use std::stoi ( http://en.cppreference.com/w/cpp/string/basic_string/stol ) to turn it into an int, and then use that int.
If the string is '#' , do whatever else you're going to do with it.
If the string is something else, do whatever you do in that case.
#include <iostream>
#include <sstream>
#include <string>
int fillScore( int ar[], constint n )
{
std::string answer;
std::cout << "Enter a maximum of " << n << " scores, concluded by a negative or #\n";
int i = 0;
while ( i < n )
{
std::cout << "Score " << i + 1 << ": ";
std::getline( std::cin, answer );
// First check for #
int pos = answer.find_first_not_of( ' ' );
if ( pos != std::string::npos && answer[pos] == '#' ) break;
// Now try to input an integer
std::stringstream ss( answer );
if ( !( ss >> ar[i] ) ) std::cout << "Only numbers are accepted.\n";
elseif ( ar[i] < 0 ) break; // what did you intend here?
else i++;
}
return i; // returns the actual number input (last good index + 1)
}
//======================================
int main()
{
constint MAXNUM = 100;
int a[MAXNUM];
int num = fillScore( a, MAXNUM );
std::cout << "\nNumber entered: " << num << '\n';
std::cout << "Scores: ";
for ( int i = 0; i < num; i++ ) std::cout << a[i] << " ";
}
Enter a maximum of 100 scores, concluded by a negative or #
Score 1: 10
Score 2: 25
Score 3: 15
Score 4: #
Number entered: 3
Scores: 10 25 15