0

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;
}
3
Contributors
9
Replies
10
Views
6 Years
Discussion Span
Last Post by bookmark
0

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)

Edited by jonsca: n/a

0

Should the function definition have a type?

Edited by seanbp: grammar

0

Should the function definition have a type?

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

0

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.

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

:)

Edited by seanbp: forgot one line

0
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.

Edited by jonsca: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.