I'm in dire need of help with coding this function/small program. I have 2 codes that I am working with just need one tha works well. Any help that can be provided would be appreciated greatly.
How it should work:
Write a function that accepts a pointer to a string as an argument and returns the number of words contained in the string.
Must actual count the number of words. User must be able to input a stringand then pass the string to the function. The function must also display the average number of letters in each word.
Codes that I am working with below:
1.)
----------------------------------------------------------------------------------------------------------------
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
int main ()
{
const int size = 5;
char WordString[size];
string sentence;
int wordlength = 5;
int wordcount = 0;
int i = 0;
cout<<"Enter a string or sentence: ";
cin.getline( WordString, size );
while( i <= sentence.length() )
{
if( isalpha( sentence[i] ))
{
wordlength++;
}
else if ( wordlength > 0 )
{
wordcount++;
wordlength = 5;
}
i++;
}
cout<<"There are " << wordcount << "words in this sentence."<< endl;
cin.get();
return 0;
}
_______________________________________________________________________
2.)
Tried working with this one also but program doen't allow me to do anything. Exits to early
-----------------------------------------------------------------------------------------------------
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
int main()
{
char abcd[100]; //string
int wordcnt=0; //word counter!
fflush(stdin);
cout << "\nEnter string: ";
cin.getline(abcd,wordcnt);
if(abcd[0]!=' ') wordcnt++; //account for the first word
for(int i=0; abcd[i]!='\0'; i++)
{
if(abcd[i]==' ')
{
//increment i until non-space char is found
while(abcd[i]==' ')
i++;
//account for spaces at end and increment wordcnt
if(i <= strlen(abcd))wordcnt++;
}
}
cout << "\n\nWord Count: " << wordcnt;
cin.get();
return 0;
}