Capitalising

Hey, I am a beginner and have a q. i have a task to leave only first capital letter in each sentence from given uppercase text in file. My code works, but since text in file is in separate lines, <char_array[0]=toupper(char_array[0]);> capitalises firs letter of each line. How can i avoid capitalising first letter of second line?cuz its not the beginning of the sentence? my text:
AMBITIONI DEDISSE SCRIPSISSE IUDICARETUR.ARAS
MATTIS IUDICIUM PURUS SIT AMET FERMENTUM.AONEC
SED ODIO OPERAE, EU VULPUTATE FELIS RHONCUS.

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
   void abc(){
     for(int i = 0; i < n; i++){
    int n = txt[i].length();
    transform(txt[i].begin(), txt[i].end(), txt[i].begin(), ::tolower);
    char char_array[n];
    strcpy(char_array, txt[i].c_str());

    char_array[0]=toupper(char_array[0]);

     for (int j = 0; j < n; j++){


        if(char_array[j]=='.'||char_array[j]=='?'||char_array[j]=='!'){
            char_array[j+1]=toupper(char_array[j+1]);
        }

            cout << char_array[j];
     }


     }}
Last edited on
Your code is too complex and won't work if there are any spaces after the period, exclamation mark or question mark.

You should deal with character by character, not store them in arrays.

Scan your input, keeping a "state" for capital letters which is set to true whenever the character encountered is one of .?! and set to false after writing any alphabetic letter. As a character is read, put it in upper or lower case according to your current "state" of capitalisation.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cctype>
using namespace std;

char title( char c )
{
   static bool Capital = true;
   string sentenceEnd = ".?!";
   if ( sentenceEnd.find( c ) != string::npos )
   {
      Capital = true;
   }
   else if ( isalpha( c ) )
   {
      c = Capital ? toupper( c ) : tolower( c );
      Capital = false;
   }
   return c;
}

int main()
{
// ifstream      in( "myfile.txt" );
   istringstream in( "AMBITIONI DEDISSE SCRIPSISSE IUDICARETUR. ARAS\n"
                     "MATTIS IUDICIUM PURUS SIT AMET FERMENTUM. AONEC\n"
                     "SED ODIO OPERAE, EU VULPUTATE FELIS RHONCUS.\n" );
   ostream &out = cout;

   for ( char c; in.get( c ); out.put( title( c ) ) );
}
Last edited on
You could also use a regular expression
 
std::regex(R"((.+)\s*[\.\?\!])");


And just get the sentence from the capture group. You can then make the first one uppercase and all others lowercase. Then you can recursively do this for all the sentences
Last edited on
Topic archived. No new replies allowed.