------------------------------------------------------------------------------
MC logo
Printing C++ Strings
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Hello, World! (Plain C)] [Average C I/O] [Printf Demo] [Problems With C I/O] [Looping On Read] [Convert To Upper Case] [Indent and Blank Remover] [Reading Lines] [Safer Line Reading] [Printing C++ Strings]
strmix.cpp
#include <string>
#include <stdio.h>

/*
 * This just shows how to use C++ strings with plain C I/O: You must use the
 * c_str() method to convert to plain C string.  This method is useful in
 * many places where you have a C++ string you need to process with an
 * existing library or system call that wants a plain C string.
 */

main()
{
        std::string fred = "This is a string of characters.  Do you like it?";

        int pos = 0;
        int linect = 0;
        while(pos < fred.length()) {
                printf("[%s]", fred.substr(pos,4).c_str());
                if(++linect >= 5) {
                        linect = 0;
                        putchar('\n');
                }
                pos += 4;
        }
        if(linect) putchar('\n');
}