Help with c string hw please.

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
  using namespace 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;




} 
finds length of string:
1
2
3
4
char* p = name;
while(*p)
    ++p;
int size = p - name;
Last edited on
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.)

http://cplusplus.com/reference/cctype/isalpha/
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 )
how is this, i dont have a complier to check if its really working
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
#include <cstring>
char name[50]= {};

int size;
int main()
  
{
cout << "Please Enter Your First name" << endl;
cin >> name;
char* p = name;
while(*p)
    ++p;
  size = p - name;
cout << "Number of Characters are : " << size << endl;

}
Last edited on
It is just that I do not believe that typical school assigment will be that deep

I think it's hypocritical to say that after you posted pointer arithmetic showoff code, but OK.
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.
Last edited on
kiste5 wrote:
how is this, i dont have a complier to check if its really working

http://ideone.com/ to get you by for now.
Topic archived. No new replies allowed.