I have to write a program using a while loop to read a string that represents an identifier character by character. I know how to do while loops but that is all im challenged with. I would love explanations as i would love to learn this stuff and get better with it. Thanks in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//Enter an identifier and identify if it is
//a valid C++ identifier and follows the rules of C++ identifiers
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string identifier;
cout << " Please enter a C++ identifier and press enter immediately after." << endl;
cin >> identifier;
cin.get();
return 0;
}
here are some of the rules , you can use an if statement to check if they are met
The rules of naming identifiers in C++ :
-----------------------------------------------
1. C++ is case-sensitive so that Uppercase Letters and Lower Case letters are different
2. The name of identifier cannot begin with a digit. However, Underscore can be used as first
character while declaring the identifier.
3. Only alphabetic characters, digits and underscore (_) are permitted in C++ language for
declaring identifier. Other special characters are not allowed for naming a variable /
identifier
4. Keywords cannot be used as Identifier.
How to read a string character by character?
use a loop and an index to access the string just like in arrays, or you could use a range based for loop that will automatically do the indexing for you.
Thanks for the rules i know of those but i am not sure of how to make it into a code. For example the output would have my cout statement above and then i would enter an identifier and within seeing it it would tell if it is a valid identifier or not. For example if i enter _3digitone in the cin operator, the statement would be that this isn't valid.
You could try with a logic like this:
- if in your string you find something which is not a letter or a digit, than the identifier is bad (suggestion: std::string::find_first_not_of() ) http://en.cppreference.com/w/cpp/string/basic_string/find_first_not_of
- if the first character is not a letter or an underscore, than the identifier is bad.
Are there further checks needed?
Do you need the code?