C#
C++
SQL

0 Comments:

Post a Comment



<< Home

C++ String Stream

After using C++ for many years, I found myself still using the printf family of C functions for formatting. When I started my new job this last March, I noticed the other folks are big on using string streams. I've been trying to ween myself off sprintf and wanted to share some very simple examples.
#include <iostream>
#include <sstream>

using namespace std;

int main(int argc,char** argv){
    ostringstream buffer;
    buffer << "Testing " << 1 << 2 << 3 << endl;
    cout << buffer.str();
    return(0);
}

This code will output:Testing 123
That code isn't too bad. If that's all there was too it, I wouldn't mind using the string streams. However, advanced formatting is not so easy. But of course you can always use defines to help.

Let's say that we want a program to display today's date in MM/DD/YYYY format. Using C, this is extremely trivial.
int main(int argc,char** argv){
    time_t time1 = time(0);

    struct tm* time2 = localtime(&time1);

    printf("Today's date is: %02d/%02d/%04d\n",time2->tm_mon,time2->tm_mday,(1900+time2->tm_year));
    return(0);
}

However, I don't think the code very elegant using string streams.
#include <iostream>
#include <sstream>
#include <time.h>
#include <iomanip>

using namespace std;

#define FormatInt(number,spaces) setw(spaces) << setfill('0') << int(number)

int main(int argc,char** argv){
    time_t time1 = time(0);

    struct tm* time2 = localtime(&time1);

    ostringstream buffer;
    buffer << "Today's date is: " << FormatInt(time2->tm_mon,2) << "/" << FormatInt(time2->tm_mday,2) << "/" << FormatInt(1900+time2->tm_year,4) << endl;
    cout << buffer.str();
    return(0);
}

If there is a better way to do this I'd love to hear about it. For now, I'll use string streams at work and continue using sprintf in code at home.

Labels:

posted by Brian at