You are here:

C++/my 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 correct the spacing you can use this program:

#include <iostream>
#include <cstring>
#include<string>
using namespace std;
int main()
{
  char a[20]="hi  mom";
  int n=19;
  int x=0;
  for ( x = 0 ; x < n ; ++ x )
  {
     if ( a[x] == ' ' )
     {
        if ( a [ x ] == a [ x + 1 ] )
        {
         for ( int y = x ; y < n ; ++ y )
         {
         a [ y ] = a [ y + 1 ] ;
         if ( a [ y ] == 0 )
         {
         n = y ;
         break ;
         }
         }
         -- n ;
         -- x ;
        }
     }
     else if ( a [ x ] == 0 )
     {
        n = x ;
        break ;
     }
  }
  for (int j=0; j<n; j++)
  cout<<a[j];
  return 0;
}        

For capitalization you could use char toupper ( char ) to make sure the letters that follow a blank and are at the beginning of the string are upper case.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.