adding to an array

Pages: 12
Hi jsmith,

I know it's a long code, but the assignment was to use arrays and I'm not that far yet to use classes or std::string etc...so probably in a few weeks I will find out it could be done shorter indeed he he he

I'm starting on the vector STL now and I already find that one very much easier to use than arrays
Last edited on
Here's my solution, which needs a little polishing in find_word_boundary() to handle punctuation, numbers, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <algorithm>
#include <cassert>
#include <iostream>
#include <string>

std::string echo_word( const std::string& s ) {
    std::string result( s );
    for( std::string::const_iterator i = s.begin(); i != s.end(); ++i )
        result += '-' + std::string( i, s.end() );
    return result;
}

std::string::const_iterator find_word_boundary( const std::string& s,
    std::string::const_iterator first )
{
    return std::find( first, s.end(), ' ' );
}

void echo_phrase( const std::string& s ) {
    std::string::const_iterator first( s.begin() );
    std::string::const_iterator last( find_word_boundary( s, first ) );

    while( first != s.end() ) {
        std::cout << echo_word( std::string( first, last ) ) << std::endl;
        first = last;
        if( first == s.end() )
            break;
        last = find_word_boundary( s, ++first );
    }
}

int main( int argc, char* argv[] ) {
    assert( argc > 1 );
    echo_phrase( argv[ 1 ] );
}

Topic archived. No new replies allowed.
Pages: 12