Trying to use iddigit...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
	char studentID[10];
	float iGrade = 0;
	char LetterGrade;

	cout << "Enter your 10 digit NUMERICAL student ID:\n";
	cin.getline(studentID,11);

	if (strlen(studentID) < 10) 
	{
		cout << "You student ID is too short\n";
		exit(1);
	}

	for (int i = 0; i <= 10; i++)
	{
		if (isdigit((int)studentID[i]) == false)
		{
			cout << "Your student ID is invalid\n";
			exit(1);
		}
	}


So that's my code. But the problem is even if I enter an all numeric ID, it still tells me it's invalid. What am I doing wrong?
You've got fencepost errors. Try this:
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
26
27
28
29
30
31
32
33
#include <cctype>
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

int main()
  {

	char studentID[11];  // you need space for ten digits + one for the null char
	float iGrade = 0;
	char LetterGrade;

	cout << "Enter your 10 digit NUMERICAL student ID:\n";
	cin.getline(studentID,11);  // get max of 10 chars + one for null

	if (strlen(studentID) < 10) 
	{
		cout << "You student ID is too short\n";
		exit(1);
	}

	for (int i = 0; i < 10; i++)
	{
		if (isdigit((int)studentID[i]) == false)
		{
			cout << "Your student ID is invalid\n";
			exit(1);
		}
	}

  return 0;
  }

Good luck!
Last edited on
That worked great, thanks! But now I changed the first if statement a little to this:
1
2
3
4
5
if ((strlen(studentID) < 10) || (strlen(studentID) > 10))
	{
		cout << "You student ID is too short or too long\n";
		exit(1);//terminate the program if the id is invalid
	}

So it works fine if the ID is less than 10 digits long(it'll terminate the program) but it doesn't terminate if it's more than 10 digits. I checked it out and if you type in lets say 20 chars, it outputs 10 for the length...
The cin.getline() will only get 10 characters (plus the '\0') at once, so even if they enter > 10 characters, it will only get the first 10 (I think that is how .getline() works anyway).
http://www.cplusplus.com/reference/iostream/istream/getline/

You really should be using std::strings.
1
2
3
4
5
6
  string studentID;
  ...
  getline( cin, studentID );

  if ((studentID.length() < 10) || (studentID.length() > 20))
    ...
Topic archived. No new replies allowed.