trouble with a project

Write your question here.
I want for any user to put in only 9 digits and if its less than nine digits or more than nine digits, i want for my program to redirect them to input only nine digits before going through the rest of the program. I know it requires a loop but in my class we haven't covered more advanced issues

Put the code you need help with here.

cout << "PLEASE ENTER THE PATIENT 9 DIGIT MEDICAL RECORD NUMBER:" << endl;
cin >> mrn;
if (mrn <= 111111111)
{
cout << "Please enter a nine digit medical record number." << endl;
}
if (mrn >= 999999999)
{
cout << "Please enter a nine digital medical record number." << endl;
}
I'm also a learner :), but to my mind, you will need a recursive function for that
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;

void medical(int mrn) {
	if (mrn >= 100000000 && mrn <= 999999999) {
		cout << "entering 9-digit medical number was successful!\n";
	}
	else {
		cout << "PLEASE ENTER THE PATIENT 9 DIGIT MEDICAL RECORD NUMBER, YOUR ENTERED NUMBER ISN'T 9-DIGIT ONE:\n";
		cin >> mrn;
		medical(mrn);
	}
}

int main() {

	int mrn;
	cout << "PLEASE ENTER THE PATIENT 9 DIGIT MEDICAL RECORD NUMBER:\n";
	cin >> mrn;
	medical(mrn);

	system("pause");
	return 0;
}


the code above takes a number from user and using function medical, determines whether it's 9-digit one or not. if it is, prints success, if not, prompts the user to input another number and the function calls itself for the new number
Recursion and looping often amount to the same thing. Here, just a while loop.

Note: I wasn't sure about the limits, this code allows 100000000 and 999999999 which are both valid 9-digit numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

int main()
{
    unsigned int mrn;
    
    cout << "PLEASE ENTER THE PATIENT 9 DIGIT MEDICAL RECORD NUMBER:" << endl;
    
    while (!(cin >> mrn) || (mrn < 100000000) || (mrn > 999999999))
    {
        cout << "Invalid input\nPlease enter a nine digit medical record number.\n";
        cin.clear();               //. reset status flags
        cin.ignore(1000, '\n');    // discard input until end of line
    }

    cout << "Thank you\nMedical Record Number: " << mrn << '\n';

}
Last edited on
@nick2361 I think you will need to pass the parameter by reference, or the value entered is simply thrown away.
Another possibility is to enter the user input as a string, check that the length is 9 characters, and that all of them are numeric. That would allow numbers such as "000000000". You might further add a check that the very first character of the string was not '0'.
Last edited on
@chervil, if we want to use the applied number in main(), yes we will have to pass by reference, just adding "&" will do: void medical(int &mrn).
Last edited on
Topic archived. No new replies allowed.