Hi I'm trying to make a program that returns the number of letters in a string but it seems that the function I have is not working as it returns 0 every time. Can someone check what I'm doing wrong? Thanks in advanced.

#include<iostream>
#include<string>
using namespace std;

unsigned letters(const string a);

int main(){
	int i;
	string a;
	cin >> a;
	cout << letters(a);
	system("pause");
}


unsigned letters(const string a){
	int i;
	int countL = 0;
	for(i=0;a[i]!='\0';i++){		
		if (a[i] >= 'A' && a[i] <='Z' && a[i] >= 'a' && a[i] <= 'z')
			countL++;
}
	return countL;
}

std::string s don't (EDIT: necessarily) end in '\0' so you have to check and see if you've exceeded the length (which is accessed by the string object's .length() method)

Should the function definition have a type?

Should the function definition have a type?

unsigned is a type, unless I'm misunderstanding your question...

The int is implied. Don't remember reading that. If there's no null terminator wouldn't the code run an infinite loop? bookmark says it returns.

yeah it returns a 0

for (i = 0; i < a.length(); i++) 
if ((a[i] >= 'A' && a[i] <= 'Z') || (a[i] >= 'a' && a[i] <= 'z'))

:)

for (i = 0; i < a.length(); i++) 
if ((a[i] >= 'A' && a[i] <= 'Z') || (a[i] >= 'a' && a[i] <= 'z'))

:)

Good catch, I hadn't gotten that far yet, though you should at least give him/her the means to figure out why the logic was wrong.

The code that seanbp made it work. thanks seanbp.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.