In a better way and to make the life easier, you could do the same stuff with the help of std::stringstream
and std::vector
:
#include <iostream>
#include <sstream>
#include <vector>
int main(void) {
std::string string;
std::string temp;
std::vector<std::string> words;
int counter = 0;
std::cout << "Enter a string: ";
std::getline(std::cin, string);
// a string stream to separate each word
std::stringstream ss(string);
// pushing the separated words (by space) into a dynamic array
while (ss >> temp)
words.push_back(temp);
// comparing each array of 'words' (where each separated words are stored
// as a type of 'std::string'
for (size_t i = 0, len = words.size(); i < len; i++)
if (words.at(i) == "a" || words.at(i) == "an" || \
words.at(i) == "A" || words.at(i) == "An")
counter++;
// if no articles found, i.e. the counter is zero
if (counter == 0) {
std::cout << "Sorry, there were no articles found.\n";
return 0;
}
// otherwise...
std::cout << counter << " number of articles were found!\n";
return 0;
}
A sample output is as follows:
Enter a string: A great scientist, Newton experimented something on an apple.
// _^___________________________________________________^^_______
2 number of articles were found!
Also, avoid the usage of bits/stdc++.h
, it's neither the part of Standard C++ nor a good convention to use as directed in @ChrisMM's comment in this post.
Using using namespace std
for smaller programs where the chance of naming ambiguity is negligible, is good, but better avoid in large programs.