Tuesday, 19 August 2008

Diving into C++

My first C++ script to practice string manipulation, standard input/output and formatting. It compiles with GCC using g++ [name.c] -o [name] under linux. Note that to meet ANSI C compliances, it is necessary to use not in the preprocessor directives, hence library function calls are prefixed with 'std::'. Using the 'using namespace std;' statement removes the need to prefix iostream objects/methods with 'std::' - similar to C#.

//*******************************************************
// Copyright (c) Christopher Cross 2008
// Format Name to fit within
// confines of Envelope window
// (An example of C++ string/cin/cout manipulation)
//*******************************************************

#include
#include
#include

#define INCOME_TAX 40
#define FORENAME_LENGTH 30
#define SURNAME_LENGTH 30
#define ENVELOPE_LENGTH 15

void fitOnEnvelope(char * first, char * last);

using namespace std;

int main(void)
{
char firstName[FORENAME_LENGTH];
char lastName[SURNAME_LENGTH];

cout << "Enter First Name:" << endl;
cin.get(firstName, 15);
cin.get();
cout << "Enter Last Name:" << endl;
cin.get(lastName, 15);
cin.get();
fitOnEnvelope(firstName, lastName);
return 666;
}

void fitOnEnvelope(char * first, char * last)
{
int size = strlen(first) + strlen(last);
char border[4] = "***";

if(size < (ENVELOPE_LENGTH - 1)) //allow for \0
{
cout << setw(ENVELOPE_LENGTH)
<< setiosflags(ios::right)
<< first << " " << last << endl;
}
else
{
char abbrev[ENVELOPE_LENGTH-3]; //allow for wspace, period, \0
strcpy(abbrev, last);
cout << setw(ENVELOPE_LENGTH)
<< setiosflags(ios::right)
<< first[0] << ". " << abbrev << endl;
}
return;
}

2 comments:

Smiler said...

Can you not use the 'using' keyword in ASCI C++ then? Your comment was a little confusing.

I.e. 'using std', then you can just type cout without std:: (I think - it's been years since I've looked at C++)

Chris said...

yup, you're quite right, I realised shortly after writing this post - should have updated it. Adding:

using namespace std;

gets around the tedium of prefixing iostream methods with 'std::' similar to C#.

Recently I've been learning from a proper book (C++ Primer Plus, Stephen Prata); rather than misleading web tutorials!