fork download
#include 
#include 
#include 
#include 

std::istringstream in(
    "Hi all,\n"
    "\n"
    "I would like to write a program to count the number of characters, "
    "words, and paragraphs(or newlines) in a file.I have the characters "
    "counting correctly and the newlines counting correctly but I am "
    "stuck on how to count the words, I would like to store the words in "
    "an array to hold the size of the word(i.e.the number of letters "
    "influences where its stored in the array) then I need to sum up the "
    "array and display the output.\n"
    "\n"
    "Thanks in advance for the help."
);

int main()
{
    std::size_t characters = 0;
    std::size_t words = 0;
    std::size_t paragraphs = 0;

    bool in_word = false;
    bool in_paragraph = false;

    char token;
    while (in.get(token))
    {
        if (std::isspace(token))
        {                               // whitespace
            in_word = false;

            if (token == '\n')
                in_paragraph = false;
        }
        else
        {                               // non-whitespace
            ++characters;

            if (!in_paragraph)
            {
                in_paragraph = true;
                ++paragraphs;
            }

            if (!in_word)
            {
                in_word = true;
                ++words;
            }
        }
    }
    
    std::cout << "Characters:" << std::setw(5) << characters << '\n';
    std::cout << "Words:     " << std::setw(5) << words      << '\n';
    std::cout << "Paragraphs:" << std::setw(5) << paragraphs << '\n';
}
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Characters:  381
Words:        87
Paragraphs:    3