Hello,

I am sorry if I am boring you, but I know of toupper() and tolower(). Is there a toProper() in C++?

Proper case is the first letter of the word is in uppercase while all other letters of the word are in lowercase.

Is there a way I can convent what the user inputs from the keyboard to "Proper" case?

This has to work on strings not characters like toupper() and tolower().

Thanks a Million.

Recommended Answers

All 2 Replies

Here is an exmaple to help you.

#include<iostream>
using namespace std;

int main() {
	char str[] = "one two three four five";
	bool wasSpace = 1;
	for (int i = 0; str[i]; i++) {
		if (wasSpace)
			str[i] &= str[i] >= 'a' && str[i] <= 'z' ? 223 : 0;
		wasSpace = str[i] == ' ';
	}
	cout << str;
	cin.ignore();
	return 0;
}

>Is there a toProper() in C++?
No, you have to write it yourself. However, it's not terribly difficult to do:

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

bool isWordChar ( char c )
{
  const std::string word_chars =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  return word_chars.find ( c ) != std::string::npos;
}

std::string toProper ( const std::string& src )
{
  std::string dst = src;
  std::string::size_type i = 0;

  while ( i < dst.size() ) {
    // Skip non-word characters
    while ( i < dst.size() && !isWordChar ( dst[i] ) )
      ++i;

    if ( i < dst.size() )
      dst[i++] = std::toupper ( (unsigned int)dst[i] );

    // Find the next word boundary
    while ( i < dst.size() && isWordChar ( dst[i] ) )
      ++i;
  }

  return dst;
}

int main()
{
  std::cout<< toProper ( "this is a test" ) <<'\n';
}

With this approach you can even specify what you want a "word" to mean.

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.