C++/question

Advertisement


Question
write a program that reads in a sentence of up to 100 characters and outputs the sentence with spacing corrected and with letters corrected for capitalization?
#include <iostream>
#include <cstring>
#include<string>
using namespace std;
int main()
{
  char a[20]="hi  mom";
  int n=19;
  int x=0;
  if(a[x]==' ')
  {
   if (a[x]&&a[x+1])
  {
       while ((a[x])&&(a[x+1]))
     {
        a[x]=a[x+1];
        
       }
     x--;
   }
  }
  for (int j=0; j<n; j++)
     cout<<a[j];
  return 0;
}  

Answer
to read in a sentence, read character by character till a period is encountered.

   std::string sentence ;
   char ch ;
   while( std::cin.get(ch) && ( ch != '.' ) )
        sentence += ch ;
   sentence += '.' ;

i presume 'spacing corrected' means replace multiple spaces by a single space. using a stringstream is the easiest way to do this (#include <sstream>) :

   std::istringstream stm(sentence) ;
   std::string word ;
   std::string corrected_sentence ;
   while( stm >> word ) corrected_sentence += word + ' ' ;


and 'corrected for capitalization' means the first letter of the first word is capitalized, the rest are not capitalized.

   corrected_sentence[0] = std::toupper( corrected_sentence[0] ) ;

   for( std::size_t i = 1 ; i < corrected_sentence.size() ; ++i )
       corrected_sentence[i] = std::tolower( corrected_sentence[i] ) ;

for std::toupper() and std::tolower(), #include <cctype>  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.