[Solved] How to create a program that counts number of works and characters in a line in C++ WITHOUT using #include [closed]


For counting characters, you can read the characters in one-by-one (see istream::get()), maintaining a count until you hit an end-of-sentence marker. That means something like (pseudo-code, since only classwork tends to have these bizarre limitations and you’ll learn very little if we do the work for you):

# Initial count.

set charCount to 0

# Process every character until end of sentence.

set ch to getNextChar()
while ch is not end-of-sentence:
    # Each character increments the count.

    add 1 to charCount

    # Go get next character.

    set ch to getNextChar()

At the end of that loop, you have the character count (including spaces).

Getting a word count is slightly trickier but you can do it by simply maintaining the state of the last character (state being either SPACE or NONSPACE).

A word ends when you transition from NONSPACE to SPACE. That means you can use conditional statements within that loop to increment a wordCount variable on one of those transitions.

Just watch out for the edge case when you hit the end-of-sentence marker and the previous state was NONSPACE, that’s also a word ending.

A good start for that code for counting both characters and words would be (though it’s up to you to implement and debug):

# Initial counts and state.

set charCount to 0
set wordCount to 0
set prevState to SPACE

# Process every character until end of sentence.

set ch to getNextChar()
while ch != end-of-sentence:
    # Characters are easy.

    add 1 to charCount

    # Get state of current character.

    if ch is a space:
        set currState to SPACE
    else:
        set currState to NONSPACE

    # Word end detected when transition NONSPACE to SPACE.

    if prevState is NONSPACE and currState is SPACE:
        add 1 to wordCount

    # Update previous state and get next character.

    set prevState to currState
    set ch to getNextChar()

# Edge case, word at end of sentence.

if prevState is NONSPACE:
    add 1 to wordCount

0

solved How to create a program that counts number of works and characters in a line in C++ WITHOUT using #include [closed]