Use c++ to convert the first letter of each word to uppercase

  • 2020-04-02 01:06:43
  • OfStack

Using C++, read in an English text and capitalize each English word in the text.
This procedure practice from a text reading stream, using fstream. In the text conversion process, isalpha () -- whether it's a letter or not, toupper () -- is used to convert the two functions (single character operations for string objects) to uppercase characters. Similar operations are isalnum() -- whether it's a letter or a number, iscntrl() -- whether it's a control character, isdigit() -- whether it's a number, isgraph() -- whether it's not a space, but it can print, islower() -- whether it's a lowercase letter, isprint() -- whether it's a printable character, ispunct() -- whether it's a punctuation mark, isspace() -- whether it's a space, isupper() -- whether it's an uppercase letter, Isxdigit () -- whether it's a hexadecimal number, tolower() -- converts to lowercase.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 //Read the file to the console
 char buffer[500];
 string str;
 ifstream ifs; //Provide file reading function
 ifs.open("d:\com.txt",ios::in);//In -- open the file and read it
 cout << "d:\com.txt" << " As follows: " << endl;
 while(!ifs.eof())  //Determine if the end of the stream is reached
 {
  ifs.getline(buffer, 500, 'n'); //Characters up to 256 or end at a newline
  str = buffer;
  if (str.empty()) //If an action is empty, skip
  {
   continue;
  }
  else
  {
   if (isalpha(str[0]))
   {
    str[0] = toupper(str[0]);
   }
   for (string::size_type index = 1; index != str.size(); index++)
   {
    //STR [index] is capitalized if it is not preceded by a letter
    if (isalpha(str[index]) && !isalpha(str[index-1]))
    {
     str[index] = toupper(str[index]);  //Notice that we're going to assign a value here after the transformation
    }
   }
  }
  cout << str << endl;
 }
 ifs.close();
}


Related articles: