I can't get all the identifiers to come out not right

For example when i enter _3d digit, it comes out saying this is valid. I am confused as to why

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
34
35
36
37
38
39
40
#include <iostream>
#include <string>
using namespace std;

bool isValidIdentifier(string key) {
	char c;
	if (key.length() <= 0) {
		return false;
	}

	for (int i = 0; i < key.length(); i++) {
		c = key[i];
		if (isalnum(c) == false
			&& c != '_') {
			return false;
		}
	}

	c = key[0];
	return isalpha(c) || c == '_';
}
int main(int argc, char** argv) {


	string identifier;
	cout << "Enter a valid c++ identifier. \n";
	getline(cin, identifier);


	if (isValidIdentifier(identifier)) {
		cout << "this is valid\n";
	}
	else {
		cout << "this is not a valid identifier.\n";
	}
	cin.get();
	cin.get();
	return 0;
}
  
Have you tried looking at the code and thinking about what happens when you enter _3d ?

Enter string _3d

Pass _3d to function

_3d is not zero characters or less in length, keep going

Look at first character, _
1
2
if (isalnum(c) == false
			&& c != '_') 

Is _ alphanumeric? No, so this is:
1
2
if (true
			&& c != '_') 

Is _ not equal to '_' ? It IS equal to '_', so this is:
1
2
if (true
			&& false) 


so keep going. repeat check with 3 and d. Those are both alphanumeric, we still don't return false.

At the very end, you check the first character again, and you return true if is '_'. Did you mean it to return false if the first character is '_' ?

Last edited on
Why do you think _3d is not a valid C++ identifier?

The following compiles correctly indicating _3d is a valid C++ identifier.
1
2
3
4
int main ()
{   int _3d;
    return 0;
}

Last edited on
Topic archived. No new replies allowed.