0

I need to count words in a string variable by counting spaces. Also i need to count sentences by counting dots. I use member function at() to get a character and compare it but for some reason my Xcode compiler won't let me do that. here is my header file:

#ifndef SPEECHANALYST_H
#define SPEECHANALYST_H

#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;

namespace marina
{
class SpeechAnalyst : public string
{
public:
SpeechAnalyst () : std::string()
{};
void clear( ); // resets everything...
void addData( char * stuff );
void addStringData( std::string stuff );

int getNumberOfWords( ) const;
int getNumberOfSentences( ) const;

friend ostream& operator << ( ostream& outs, const SpeechAnalyst & sa );  //         prints the data seen so far!

private:
std::string myData;


};
}
#endif /* SpeechAnalyst_h */

And this is my implementation file:

 #include "SpeechAnalyst.h"
 #include <stdio.h>
 #include <iostream>
 #include <string>
 using namespace std;


namespace marina
{
   void SpeechAnalyst::clear( )
   {
     myData.clear();
   }



    void SpeechAnalyst::addStringData( std::string stuff )
   {
      myData += stuff;

   }

   void SpeechAnalyst::addData( char * stuff )
   {
    string line;
    line=stuff;
    myData += line;
    }

    int SpeechAnalyst::getNumberOfWords( ) const
    {
    int i,words=0,sentence=0;
    for (i=0; i<myData.length(); ++i)
       {
        if (myData.at(i) == " ")
            words++;
        }
      return words;
    }


    }

So the errors that compiler sees are: 1)Result of comparison against a string literal is unspecified (use strncmp instead) 2)Comparison between pointer and integer ('int' and 'const char *')

Both of the error are at the line "if (myData.at(i) == " ")"

Marina
  • 49
  • 1
  • 8

2 Answers2

2

I don't think you're far off with your own solution.

Try this:

if (myData.at(i) == ' ')

Instead of yours:

if (myData.at(i) == " ")

With " " you're creating an array of characters versus ' ' which creates one character.

Chringo
  • 131
  • 2
  • 12
0
int number_of_spaces = 0;
int number_of_dots = 0;
for (auto& iter : input_text)
{
    if (iter == ' ')
    {
        number_of_spaces++;
    }
    else if (iter == '.')
    {
        number_of_dots++;
    }
}

This code counts the number of white spaces and dots. It doesn't count like tab new line or carriage return.

Shravan40
  • 8,922
  • 6
  • 28
  • 48