Wrote a program to read your name.Count the number of letters in your name. use while or for loops do not sure strlen. helpl please im a beginner
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
usingnamespace std;
#include <cstring>
int main()
char name[50]= {};
int somenumber;
{
cout << "Please Enter Your First name" << endl;
cin >> name;
cout << "Number of Characters are << somenumber << endl;
}
The reason why you must not use std::strlen() is because you have to count the letters.
std::strlen() gives you the length of the string, no matter what it contains: letters, digits, punctuation, spaces.
You must go through the entire contents of the string and check if they're letters. When you find a letter, increment (meaning "add one to") a counter.
To check if a char is a letter, you can use the std::isalpha() function from cctype.
You reach the end of a string when the current char is equal to '\0'. (Hello Disch.)
I believe that they should not use strlen because they should learn how c-like strings are represented in memory, not because of possibility of encountering non-characters in name (yes I know about hyphens and apostrophes and spaces and whatever else. It is just that I do not believe that typical school assigment will be that deep )
Why are there is so many globals?
Move them inside main()
Declare them when they are needed:
1 2 3 4 5 6 7 8 9 10 11
int main()
{
cout << "Please Enter Your First name" << endl;
char name[50];
cin >> name;
char* p = name;
while(*p)
++p;
int size = p - name;
cout << "Number of Characters are : " << size << endl;
}
And Catfish asks important question: does name Kennedy-Warburton contains 16 or 17 characters? Should hyphen counts? If it should not, then my code will not suit you.
EDIT:
I think it's hypocritical to say that after you posted pointer arithmetic showoff code
This is simplified gcc strlen() implementation (before they got to some extremely fast black magic). Or just BSD implementation.