0

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.

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Narue
0

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;
}
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.

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.