Tuesday, May 21, 2013

Introduction to C++

Hello Alchemists!

I have retrieved some homework assignments from my college days, where I took a course named UNIX Network Programming. The goal of this course was to teach students how to write programs which can speak across a computer network, using named pipes which in the networking context are referred to as "sockets". This program uses a simple socket which opens a text file for writing. It serves as a building block for future assignments.

Over the next several weeks I will be adding comments to these programs and publishing them on the blog, as I have done for this first assignment.

If you really want to challenge yourself, you can go beyond simply reading the program, and try compiling it and running it yourself. You can either use Cygwin as an environment in Windows, or try a compiler on a UNIX/Linux Computer. The next step would be to modify it, and test your alterations.

If you recall in class I advocated the use of Google and Wikipedia to study not only computer science, but any topic which you wish to learn about. One website which I found on Google is the following tutorial, which is not only a great start for C programming, but is absolutely free and always available for use.

Many people will wish you luck, however in my experience you have to make your own luck, which takes plenty of hard work! The moment you quit is when you have truly failed.

C Programming Tutorial


/*
Filename :  01.cpp
Abstract : Write data into a file using terminal input.
Programmer : Capri Gomez
*/

/* Library calls which provide functions for this program */
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

/* Declares main function */
int main() {

/* Declares a string for later use */
string mystring;
/* Declares a output pipe to a file */
ofstream mfile;
/* Print's a string to the Terminal (Standard Out) */
cout << "Please type some data to write to a file:\n";
/* Defines a text file for use with the output pipe (Trunc means Truncate, which empties the file if it already exists) */
mfile.open("hi.txt", fstream::trunc);
/* Retrieves string from Standard Input and writes it to mystring*/
getline (cin, mystring);
/* Writes the string to the file we declared earlier */
mfile << mystring;
/* Close the File */
mfile.close();
/* Returns the Number 0 which can be used to make other decisions (N/A) */
return 0;
}

No comments:

Post a Comment