/*
Program for counting number of words in Entered "STRING".
*/
#include<iostream>
using namespace std;
//Function declaration
int wordCounter(char*);
int main()
{
int length;
//for getting length
cout << "Enter Approximate Sentence length?\t";
cin >> length;
//For clearing buffer
cin.ignore();
char *sentence=new char[length]; //declares new character array of entered length on heap
//For Inputting Sentence
cout << "Enter Sentence?\n";
cin.getline(sentence, length);
//For displaying result
cout<<"Number of words in entered Sentence are "<< wordCounter(sentence);
cout << endl;
return 0;
}
//Function definition
int wordCounter(char* sentence)
{
int count = 1;
//For calculating number of words
for (int i = 0; sentence[i] != '\0'; i++)
if (sentence[i] == 32) //ASCII Code of space is 32.
count++;
return count;
}
OUTPUT
No comments:
Post a Comment