Saturday, August 29, 2015

Code and the modern IDE

What is the difference between

#‎include‬ <stdio.h> 

int main(){ 
     char name[40]; 
     gets(name); 
     if((int) sizeof(name) > 39*4){ 
         printf("Something went wrong!!!"); 
        }
      else{ 
         printf("%s\n", name); 
        } 
}

and

#‎include‬ <stdio.h> 

int main(){ 
     char name[40]; 
     gets_s(name); 
     if((int) sizeof(name) > 39*4){ 
         printf("Something went wrong!!!"); 
        }
      else{ 
         printf("%s\n", name); 
        } 
}

Not much, the first example is an example of a primitive way to check the input for buffer overflow condition.  Unfortunately, the function gets() has a buffer overflow condition problem, so it is useless to rely on this function for checking the length of the input.  Programmers should use gets_s() function call instead.  These days, modern IDEs will check for old and deprecated functions that are not secure to use, so programmers will not make these kind of mistakes.  For example, Visual Studio, I used VS2013 in this example, will not even allow the re-processor to compile this code into an executable unless we force the code of the compiler to ignore security checking.


Why would someone run this command if the previous code was compiled as driver.exe?
python -c "print '\x42'*41" | driver.exe
 
Note: In order to compile the first example code, you might have to turn off error messages that might not allow you to compile it.  This can be done in the project's property ( see image below ) or by adding the code below before the pre-processor to the project in Visual Studio.

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
 

Wednesday, April 1, 2015

Challenge Question 1: Loop ( break / continue )

What does this code do?

#include<iostream>

using namespace std;

int main(){
    int MAX = 50;
    int counter = 0;

    while (counter++ < MAX){
        if (counter % 2 != 0)
            continue;

        cout << counter << endl;
       
        if (counter == 20)
            break;
    }
    return 0;
}

Tuesday, March 3, 2015

Random numbers

See the randomness of C++ generated random numbers by providing a fixed seed and a random seed.  Gather the numbers in may trials and chart the results.  Charts will give you an easier way to identify patterns to evaluate the randomness.  You should modify this code to write the values to a file and import them into Excel or OO Calc to chart.

Basic steps for file implementation:
#import<fstream>

ofstream outFile;
outfile.open("output.txt");
outfile<<zero<<one<<two<<three<<four<<endl;
outfile.close();

More details:
http://intro2cs-cpp.blogspot.com/2015/03/simple-file-io.html

Code to test randomness:
//Name: <Your Name>
//Class: 2012 Fall - COSC 1415/1436.8002
//Project 0: Random Number
//Revision: 1.0
//Date: 08/15/2012
//Description: This program show the concept of random  number generation

#include <iostream>   //string input/output header file
#include<time.h>

using namespace std;  //standard class library

int main(){
  srand ( time(NULL) );         //replace the seed with a fixed number a see the effects
  int zero=0,one=0, two=0, three=0, four=0;
for(int i=0;i<10000;i++){
  Richland = rand() % 5;
  switch(Richland){
  case 0:  zero++;   break;
  case 1:  one++;    break;
  case 2:  two++;    break;
  case 3:  three++;  break;
  case 4:  four++;   break;
  }
}
cout<<"The value of zeroes: "<<zero<<endl;
cout<<"The value of ones: "<<one<<endl;
cout<<"The value of twos: "<<two<<endl;
cout<<"The value of threes: "<<three<<endl;
cout<<"The value of fours: "<<four<<endl;

  system("pause");                           //pause the program so I can read the console 
  return 0;                                  //return 0 to show end of execution 
}

Monday, March 2, 2015

Simple File I/O

This code should give you a simple recipe type of instruction to learn how to handle file input and output operations.  The biggest challenge is to understand your file system navigation with Windows Explorer and the location of your source files.

Create an input file with a simple editor like Notepad.exe and make sure you know where you save the input file to.  Do not use spaces in creating the input file name.  also, understand the input file name does not have to match the ifstream variable name.  You can name your input file anything you'd like, just type the same file name when you open the file in your code.

In this example, the input_file.txt content is 92A98.76.

Start with a skeleton program like this one and place your pseudo code into the skeleton program as comments.

Write pseudo code 
1. Include strings in case if we need to specify a string for a file name
2. This library is needed for handling file input and output,  ifstream, ofstream
    Declare variables to store data read from file
3. Declare input file variable
4. Declare output file variable
4.1 Make sure there is an input file with proper data ( read only ) and your userID has write access to output location
5. Open input and output files.  The input file should be placed on the same path with your source code.  The output file will be written into the same path as your source code.
     if you need to specify a path to the file, escape the backslash
6. Use filestream variables like we use iostream variables
7. Close input and output files

Create actual skeleton program with pseudo code copied in as comments

#include <iostream> //cin, cout, endl

 //1. include strings in case if we need to specify a string for a file name
 //2. this library is needed for handling file input and output,  ifstream, ofstream


using namespace std;

int main()
{
//Declare variables to store data read from file
   
//3. declare input file variable

//4. declare output file variable

//4.1 make sure there is an input file with proper data ( read only ) and your userID has write access to output location

//5. open input and output files.  The input file should be placed on the same path with your source code.  The output file will be written into the same path as your source code.
     //if you need to specify a path to the file, escape the backslash

//6. use filestream variables like we use iostream variables
    //cin >> x >> grade >> y;

    /*    cout << "Your test score is: " << x << endl;
        cout << "Your letter grade is: " << grade << endl;
        cout << "Your class average is" << y << endl;        */

//7. close input and output files


    return 0;
}

Complete the code by first writing the cin/cout way of reading and printing values and change that to ifstream and ofstream variables later.

#include <iostream> //cin, cout, endl

#include <string>  //1. include strings in case if we need to specify a string for a file name
#include <fstream> //2. this library is needed for handling file input and output
                   //   ifstream, ofstream

using namespace std;

int main()
{
//Declare variables to store data read from file
    char grade;
    int x;
    float y;
   
//3. declare input file variable
    ifstream inFile;

//4. declare output file variable
    ofstream outFile;

//4.1 make sure there is an input file with proper data ( read only ) and your userID has write access to
     // output location


//5. open input and output files
    inFile.open("c:\\dell\\input_file.txt");  //if you need to specify a path to the file, escape the backslash
    outFile.open("c:\\temp\\output.txt");

//6. use filestream variables like we use iostream variables
    //cin >> x >> grade >> y;

    inFile >> x >> grade >> y;

    /*    cout << "Your test score is: " << x << endl;
        cout << "Your letter grade is: " << grade << endl;
        cout << "Your class average is" << y << endl;        */
   

    outFile << "Your test score is: " << x << endl;
    outFile << "Your letter grade is: " << grade << endl;
    outFile << "Your class average is" << y << endl;

//7. close input and output files
    inFile.close();
    outFile.close();

    return 0;
}

Compile the code by placing break points before and after the read operations.  Read the values for the variables before and after the read operations to identify problems with your input file.  Note: Later on, we'll learn how to validate input and code proper exit if the input or output files can not be manipulated.

if(!inFile){                                                              //validate input
    cout<<"Input file can not be located!"<<endl;
    return 2;                         //return a value to indicate error condition                                                  
}

if(!outFile){                                                             //validate output
    cout<<"You do not have enough space to store the output or you do not have right to write output at this location!"<<endl;
    return 4;                        //return a different value to indicate error condition

}

Read file into a c_string one line at a time.

ifstream inFile;
inFile.open("input.txt");
const int SIZE = 30;
 

if (!inFile){
     cout << "Input file was not found.";
     return 2;
}
 

char lineRead[SIZE];

while (!inFile.eof()){                                         //check to see if the end of the file is reached
          inFile.getline(lineRead, SIZE-1, '\n');
          cout << lineRead << endl;
}
 

inFile.close();

Read lines in a loop and make sure the first line is not empty before entering the loop.

    ifstream inFile;
    inFile.open("input.txt");
    const int SIZE = 30;
    if (!inFile){
        std::cout << "Input file was not found.";
        return 2;
    }
    char lineRead[SIZE];
    inFile.getline(lineRead, SIZE - 1, '\n');
    while (!inFile.eof() && lineRead[0]!='\0'){    //

        std::cout << lineRead << endl;
        //for (char ch : lineRead) cout << ch << endl;           //if you want to see each character read
        inFile.getline(lineRead, SIZE - 1, '\n');
    }
    inFile.close();

Sunday, February 22, 2015

Getting started

What is the output of string INSTITUTION = "Richland \rCollege"; ?  There is also a major implementation problem with this code that you should be able to find it easy.

//Project 0: Hello World
//Revision: 1.0
//Date: 08/15/2011
//Description: Chapter 2 Summary

#include <iostream>
#include <string>
#include <math.h>
#include"header.h"

using namespace std;
using namespace richland;

int main(){

    string INSTITUTION = "Richland \rCollege";
    cout << INSTITUTION << endl;

    float PI = 3.14E0;
    cout << PI << endl;

    int value = -200;

    cin >> celsius>>value;

    fahrenheit = (float)((celsius)*(9 / 5) + 32);

    cout << fahrenheit<< endl;

    float ans = (fahrenheit - 32)*(5 / 9);

    cout << ans << endl;

    char ch = 'A';
    cout << "The \"value\" is: " <<ch<< endl;
    cout << "The value is: " << ch+1 << endl;
    cout << "The value is: " << static_cast<char>(ch+1)<< endl;

    string hello = "Hello";

    hello[3] = 'p';

    cout << "The \nstring \tis: " << hello << endl;

    return 0;
}

Pattern recognition and simple applications

You can use system("pause"); to call the pause utility in Windows systems to pause your program execution, but not many students realize that you can call other applications from C++ using this system call and have a useful application quickly.

Like translating with Google translate only requires you to look at the URL when you translate something and recognize the pattern in the URL.  You should see that you format the URL string as /#source_language/destination_language/text_to_translate.

Thus, in this example you are translating from German to English and launch Firefox to display the results.


//Required libraries
‪#‎include‬<iostream> //cin, cout, endl
#include<string> //string

//Namespace specified to avoid using std:: with cin, cout, endl, ...
using namespace std;

int main(int argc, char* argv[]){
      string program = "\"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe\"  
                                  https://translate.google.com/#de/en/ich%20bin%20ein%20kinder";
      char* prog;
      prog = &program[0];
      system(prog);                         //The magic happens here
      return 0;                                 //return integer data type to OS to indicate errorlevel
}


Look up information about an IP address.

// exceptions
#include <iostream>
#include <string>


using namespace std;
void printMe(string url){
    cout << url << endl;
    system(&url[0]);
}

int main() {
    string url = "start \"C:\\Program\ Files\ \(x86\)\\Google\\Chrome\\Application\\Chrome.exe\"\ \"http\://144\.162\.1\.180\.ipaddress\.com/#reverseip\"";
    printMe(url);

    return 0;
}


Map a location using Google maps and the location's GPS coordinates.

#include <iostream>
using namespace std;

int main()
{
    //Call Chrome browser and open a GPS coordinate
    system("\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\" HTTP://MAPS.GOOGLE.COM/?q=32.921763,-96.729206");
       
    return 0;
}

Experiment with other useful application of this simple system call and go beyond what you use it for in standard applications.  Don't be afraid of creating something new and useful even if it looks simple.