C++/question
Expert: vijayan - 4/2/2009
Questionwrite 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;
}
Answerto 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>