I have problem in counting the number of letters in the strings entered by the user. CAn anyone suggest something in the following codes?

#include <iostream>


using namespace std;

int main()
{
	char* str;
	cout<<"enter the string to count the number of letters in it.";
	cin>>str;
	cout<<str.length;
	return 0;
}

Dani AI

Generated

A few practical points that build on and : the crash comes from using an uninitialised C-style pointer for input, and switching to C++ string types is the right first step. For a reliable letter count, also handle whole-line input (so spaces aren't lost), classify characters with the C library helpers, and be careful about locales and encodings.

A safe, minimal pattern is: read the entire line, iterate its characters and test each with std::isalpha while casting to unsigned char (passing a plain char that is negative is undefined behavior for the ctype functions). For inputs that may contain non-ASCII letters (UTF-8), byte-wise classification will be wrong — decode to Unicode code points or use a library such as ICU or Boost.Locale.

Example (reads a full line and counts alphabetic characters):

#include <iostream>
#include <string>
#include <cctype>

int main() {
    std::string line;
    std::getline(std::cin, line);   // capture spaces
    int letters = 0;
    for (unsigned char ch : line) {
        if (std::isalpha(ch)) ++letters;
    }
    std::cout << letters << '\n';
}

Notes and cautions:

  • Casting to unsigned char before std::isalpha avoids undefined behavior for negative char values. See std::isalpha.
  • operator>> reads only up to whitespace; use std::getline for full lines (see the getline documentation).
  • For true Unicode-aware letter counts, do not rely on single-byte isalpha — use ICU (https://icu.unicode.org/) or Boost.Locale.

This expands on 's point about spaces and 's correction about string methods while adding safety and Unicode cautions.

Recommended Answers

All 2 Replies

Why not use a string
Add #include <string> at the top
replace char* ... with this std::string str; // and
and change your output line to this.... std::cout<<"Length == "<<str.length()<<std::endl; note that since string is a class, and str is an object of type string,
you call the string method called length. It is not a variable of string but a function hence the () after length.

However, it you want to count the letters and be a bit more careful about
spaces etc. Then there a a lot of post here and FAQs elsewhere that discuss how to proceed.

Replace: char *str; with string str; and fix: str.length with str.length()

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.