Adding File I/O to a C++ Program

We have already covered console reads from the keyboard and writes to the display using cin and cout. If you do not know how to use cin and cout, please review it before proceeding. ifstream is for an input file connection and an ofstream is for an output file connection. Once set up, they can be used the same as cin and cout respectively. Both ifstream and ofstream are C++ classes and so you need to create an instance of each class in order to use it. You have been using classes throughout your coding work with C++. The one that is easiest to explain is the class “string”. String is a class and the name of your string is the instance of the class. In your header section, it would described as:

string myString = "This is a string."

later in the code, you might want to find its length.

int len = myString.length();           // This finds the length of the string store in your instance of string.

To be fair, there are five different ways to find the length of a string. The first four are more useful than the fifth. https://www.geeksforgeeks.org/5-different-methods-find-length-string-c/

length() is considered a method of the class string and can be called by adding it to the instance of the class string by adding a “.” and then the name of the method to the instance name, as seen in the example above.

Now getting back to ifstream and ofstream.  First create the instance of each class to use.

ofstream outFile;       // define the interface to the file for writing information.
ifstream inFile;        // define the interface to the file for reading information.

The next thing to do is to open the file and seek the start of the file, again done by two methods:

   inFile.open(fileName);
   inFile.seekg(0);

Now to read something from the file one line at a time until no more lines are left in the file and divide up the line into phrases that are separated by commas:

for (string line; getline(inFile, line); ) {   // Read a line, stopping at newline (\n), keep going until EOF (end of file).
       stringstream stream(line);                // Set up the line to be readable through a stream.
      index = 0;
      while (getline(stream, word[index], ',')) {
          cout << headers[index] << word[index] << "\n";
          index++;
      }
      sum += stod(word[2]);
      count++;
 }

Output to a file is even simpler, First open the file. You have to see if the file exists. If it does, give the user the choice to write over the file or append to the file. If the file does not exist, create it.

if (isFileExist(fileName)) {
     // The file exists, so give the user the choice to start a new file or append to the existing file.
     int appendToFile = stoi(input("Do you want to:\n1) Open fresh file?\n2) Append to current file?\nChose"));
     switch (appendToFile)
     {
        case 1:
           outFile.open(fileName);     // Open an existing file, overwriting current content..
           break;
        default:
           outFile.open(fileName, fstream::app); // Open an existing file and allow appending new data.
           break;
      }
}
else outFile.open(fileName, fstream::out);  // Force the creation of the file and then open.

Once you have opened/created the file you can write to it just like you do to the console through cout.

 outFile << employee << "," << birthdate << "," << wages << endl;

The above code will write a comma separated list with three fields to one line in the file. Be sure to close the files when you are done.

outFile.close();
inFile.close();
Posted in Uncategorized | Leave a comment

Celebrating July 4th

Celebrating the 4th of July is important to me and others in the United States of America. Each country has special celebrations based on their own history. Ours is declaring independence from England, a treasonous act that could have brought death to each of the signers of the Declaration of Independence. Having an ancestor, Lieutenant Colonel Cornelius Ludlow (who was in charge of General Washington’s rear guard on the move to Valley Forge), it is a doubly important day to me. Unfortunately, a lot of revisionist history has been given out recently. That is a disservice to the memory of those who set the foundation for our nation. Yes, there were actions some of our forefathers did that were not good. But they set the stone in motion that would eventually lead to the emancipation of slaves and the various civil rights that have been put into law more recently.

Two examples of people who were anti-slavery at the time of the American Revelation were Betsy Ross and Edward Coles. Betsy Ross was the creator of the first flag of the United States. Edward Coles is a cousin of one of my ancestors and freed the slaves he inherited.

Betsy Ross grew up as a Quaker, which was opposed to slavery and helped Pennsylvania become the first state to outlaw slavery. Many Presidents, including Barack Obama, used the Betsy Ross flag in their ceremonies.

As you can see by the above picture, the Betsy Ross flag was not controversial at Barack Obama’s Inauguration. He used it to show the heritage of our United States. Betsy Ross was not a slave owner. By all indications, she opposed slavery.

Growing up, I heard the story of Edward Coles long before I knew his name. My mother would tell me about how a group of descendants of freed slaves heard about one of her cousins medical needs and offered support to my mother’s cousin to help him through his struggles. Slavery is wrong. The original Betsy Ross flag shows a field of blue with thirteen stars in a circle. This represents the equality of opportunity for all citizens of the United States. I wish all those who celebrate a wonderful fourth of July. I wish everyone all the freedom and opportunity that you desire.

Happy 4th of July!

Posted in Uncategorized | Leave a comment

C++ Hardest New Concept

I teach C++ programming to beginners. All of them seem to quickly understand simple programs like “Hello World.” They can get the logic down fairly well in simple flow charts. But where they seem to have the most struggles is with loops, especially “for” Loops. The odd thing, they seem to understand while loops and do-while loops more quickly than for loops. They understand that while loops will skip the execution of the code within the while loop if the condition is false. One gave the example of checking the chemicals in a pool to a do-while loop. You need to check the chemical level at least once. If the level is not within the specified “safe” range, then the system will do something to fix the problem and then retest. This will repeat until the chemical levels are within the “safe” parameters.

Students seem to understand that within the while(condition) statement (either at the beginning or end of the loop), the looping will continuing as long as the condition is true. The for loop is like a while loop, except it has all three main parts within the for statement:

  1. the initialization of the variable, like int i = 0
  2. the check the value of the variable to make sure that it meets the condition to continue the loop.
  3. the change of the variable by the desired amount, usually incrementing or decrementing the variable.

A for-loop looks like:

for (initialization, condition, change)

where the condition is the test to see if the looping needs to continue, identical to the condition in a while or do-while loop. a for loop may look like:

for (int i = 0; i < 5; i++) {
    // Do something 5 times.
}

The three parts of a for statement are separated by semi-colons (;), just like at the end of a C++ statement. In the above for-loop:

  1. i is specified as an integer and set to 0.
  2. The condition for the loop to continue is i being less than 5.
  3. At the end of each loop, i is incremented by one.

I tell my class that the only way they can fully understand and appreciate for loops is to write code that uses them, when they need to loop through a specific set of code a specific number of times. The first code I give them to use a for loop is to create a 12×12 multiplication table. Of course, then they want to learn about formatted printing, but that is another story.

Posted in C++, Code Reviews, Computers, Do, Mentor, Software, Uncategorized | Leave a comment

Be Our Best

What is important to each of us? What do we want to do with our lives and for what do we want to be remembered when we leave this world? I want to live as long and as healthy as possible, but I know that years are limited unless new breakthroughs are forthcoming. Whether we are a younger or older American (or some other nationality), we need to decide what we want to do with our time. There is a talk at our Church about choosing to do Good, Better, or Best. I recently found a quote by St. Jerome about this subject. It is: 

St Jerome knew how important doing are best is

The point of the talk that I mentioned before is that we need to choose how we spend our time. There can be many good things we can do, but we can choose better things to do with our time. If we know what we want to accomplish, then we can choose what is the best.

As we grow, our best grows also. I teach computer science.  On the first day of class, if a student can write, compile, and execute the “Hello World!” program, that is great an the best they can do the first day of class. After two weeks, much more is expected of each student and “Hello World!” would not be considered that student’s best effort. As we improve in any area, what is expected from each of us will increase also. We all need to grow and improve. I know there are certain areas where there may be a peak, but in most areas we can continuously improve ourselves.

We are more capable of greatness than any of us realize. What can we do to achieve this greatness? One interesting discussion that has gone on for several years is whether we should base what we do on improving our weakness or growing our strengths. One of the more recent thoughts is “Do your best and forget the rest.”  Don Clifton was one of the first authors to change the discussion from working to improve one’s weaknesses to building on a person’s strengths. Being a positive influence on our own life and the lives of those around us helps us to be our best. I believe if each of us understands our strengths and builds on those strengths, we will learn to be and do our best.

Posted in Attitude, Becoming, Do, Fulfilling Life, Goals, older Americans, Planning, Self-Worth, Uncategorized | Leave a comment

When You Have a Question – A.S.K.

I teach high school and community college computer courses. I enjoy seeing students comprehend new material. I always tell my students to ask questions. I do not mind interruptions on relevant questions about what is being discussed. I have found that if one student has a question about what is being taught, other students probably have the same question. Also, once a student has developed a question, that student will concentrate on remembering the question to ask later instead of concentrating on what is being taught. I would much prefer a student ask the question when they think of it because the question is usually triggered by the current discussion and the appropriate answer will further explain an important part of the topic. Seeing various acronyms for the word “ask” I have developed my own.

  • Assess what the concern or problem is.
  • Search for a solution.
  • Know that you will eventually receive help in finding the answer.

Assess What the Concern or Problem Is

In a classroom setting this may be a quick process, since it is usually related to what is being taught at the time. Outside of the classroom this may be a much longer and more involved process. Know why you want the answer as well as fully understanding the question.

Search for a Solution

Searching for your own solution often helps you better understand the question and the answer. When you find your own answer, it will mean a lot more to you and you will remember the answer a lot longer.

Know that You will Eventually Receive Help

In class, the answer can often come quickly, but in real life it may take awhile to find the answer. In emergencies, listening to that “still, small voice” that each of us is blessed with, along with heeding other warnings can be essential to our survival. In Idaho, the Teton Dam Collapse was a major catastrophe.

The estimates with the flooding, there should have been about 5,300 people killed in the collapse who lived in two cities downstream. There are conflicting reports on how many people were killed. It was 6-11 people who unfortunately lost there lives. One lived directly below the dam and did not really notice the problems the dam was having. Some did not heed the warnings about the approaching dam collapse until it was too late. Half were out of harms way, but went back in to save material items since they thought they had more time before the actual collapse. Sometimes the answer will come over many years. Know the difference so that you recognize an immediate answer and an evolving answer that may take up to a few years to receive.

End Note

I do not like posting incomplete entries, but I want to properly save my work for k=now and get some feedback. Hope you enjoy this.

Posted in Becoming, Do, Self-Worth, Serving, Uncategorized | Tagged , , , , | Leave a comment

What is the purpose of a pointer in programming?

The full question ended with: “Why not access the variable directly?

It depends on what you mean by “access the variable directly.” In Algol derived languages (like C, C#, C++, Pascal, Ada), the way to access a variable directly is through pointers. Java is a bit different. In Algol derived languages, you can pass a pointer to a variable in a call to a function or method. Then, whatever you do to that variable in the called function or method will alter the variable you passed by pointer in the calling code. In the Algol group of code, this is called “pass by reference” which means something totally different in Java.
FORTRAN started using pass by pointer, without actually stating what it was doing, in order to save space within the program. I learned this the hard way by passing the number “2” to a subroutine (same as a function or a method) and then changing the value of that variable in the subroutine. Since 2 in FORTRAN is stored as a pointer to the value “2” every time I would use “2” after that call, the actual value used was to what the subroutine set it.

One of the purposes of a pointer is to allow other routines to modify the value contained in the memory location(s) referenced by the pointer. As mentioned earlier, Java does not allow pointers. However, there are methods documented, for example in “How to do the equivalent of pass by reference for primitives in Java” to get around this rule for this one purpose.

In the “old” days of programming, before programmers were given a “sandbox” within to work, pointers could point to actual physical locations in memory instead of just locations relative to where your sandbox is located. With these pointers people could (and did) go in and modify the operating system on the fly. Something I do not recommend doing. This is one of the reasons Java was developed to not allow pointers.

Posted in Ada, Algol, C, C#, C++, FORTRAN, Java, Pascal, Software | Tagged , , , | Leave a comment

Which programming language did you think would be prominent, but turned out to be a complete dud?

Wayne Cook, Certified Scrum Master

After reading John Dougherty’s answer on Quora, I was tempted not to answer. But, that was only a fleeting thought.

It is hard to limit it to just one language. I was originally thinking of Ada. It was a structured language designed by committee. It came out when our team was working on SmallTalk at Tektronix. We were looking at various languages to put on our new workstation and Ada was one of the languages we studied. It was a good language but did not have an Object-Oriented component at that time. It has since added that feature, but it is a language I do not see too many people using any more. It was based on Pascal, a language that was used at Universities to teach students programming. It also is rarely used. But they all trace their ancestry back to Algol, another language designed by committee. It was a great language except for nobody being able to agree on the format for input and output commands. Algol’s high point was its use as the low level programming language for Burroughs computers. Burroughs systems were designed around Algol and when the Army asked Burroughs to write “low” level programs in assembler, they had to write an assembler interpreter in Algol. Good language, any structured language can trace its roots to Algol. This includes C, C++, Pascal, Ada, and Java. One of the best languages no one ever uses.

The language I would like to give honorable mention to is LISP. It was invented about the same time as FORTRAN and COBOL and was really popular in the Artificial Intelligence Community. It was the first language I learned after writing two major projects in FORTRAN. It is quite different than any other language using structures within parenthesis for both its programs and data. It made a comeback in the 80’s with Common Lisp and has had some derivatives that are reasonably popular. But of all the languages I have programmed, it remains the one I enjoyed the most.

Posted in Ada, Algol, FORTRAN, Java, LISP, Pascal, Software | Tagged | 2 Comments

Make a Choice

When we are young, we too often think that life will go on forever. It will not. People age. We each have choices we are given once. Keeping our options open only means we are making a choice. And often, it is not the choice that would be best for each of us. I have been happiest when I have made a good choice and not just do what is expected. The best choices are often the most difficult. Scott James posted a video that covers some of the areas about which I am thinking at this time.

The key is to DO SOMETHING! It will either be a great decision or a learning experience. It is sometimes our worst decisions that drives our most profound learning. Unless we are trying to bring our astronauts safely home from a failed lunar lander expedition, failure is an option. Think of watching little tykes learn to walk. How many times do they fall? They usually only cry if someone is watching and they know they will get sympathy. Otherwise, they are up and trying to walk instantly. We should treat our failures the same way. Analyze them, find out what went wrong, and then correct that problem. Failure unanalyzed is a problem, as is not trying at all. I remember learning to ride a bike, My why for doing so was that I did not want training wheels put on my bicycle. I failed a whole bunch of times. I was glad I was wearing long pants. We should treat life a lot like learning to walk or learning to ride a bicycle. Just go out and do it, celebrate our successes and learn from our mistakes. None of us need to sit around and feel sorry for ourselves for not achieving some goal or making a mistake. It is all part of life, and the fun in life is going out and living it fully, helping others, and sharing life with the people we find important. We all need to love failure as a learning experience and celebrate all successes of our own and each of the people about whom we care. Get off of the electronic devices and be an important person in the lives of those around us. Celebrate LIFE!

Posted in Attitude, Becoming, Do, Fulfilling Life, Goals, Health and Wellness, Mentor, Planning, Self-Worth, Serving, Uncategorized | Tagged , , , , , , , , , , | Leave a comment

Abraham Lincoln, Edward Coles, Paul McCartney, and Chris Pratt

This may be an unusual collection of people, but by the end of the article, I hope I have tied the four together. I have been thinking about the best path to the future for me. I love teaching and enjoy the interaction with the students and the wonderful people with whom I work. I plan to continue to contribute to the education of our youth for as long as God gives me the strength to do so. After my seventieth birthday, I have been thinking about what is important to me. After watching Steven Spielberg’s Lincoln, I have also been thinking of the importance of our Declaration of Independence and our Constitution, which provided for ways it could be changed to correct any injustices found therein. I believe that many of the founding fathers knew that slavery or indentured servitude of any human being was wrong, but that was the main area in which they struggled. The reason why I know that they did know what was right was in the phrase that all men are created equal. First, I will tell you a story that my mother told me when I WAS growing up. It was a story about a group of people in Chicago finding out about the problems one of my mom’s cousins in San Diego/Escondido area was having. They sent aid and comfort to him to help out where they could. Later it came out that the people who helped were descendants of slaves who were brought to Chicago by an ancestor of mom’s cousin. I was always told that the person being helped and many of the Chicago group all had the last name of Cole. Since I did meet the children of the man who was helped in Escondido, I believe that the stories were true. It was not until the internet that I was able to trace down whom I believe freed the slaves, but the internet records show an “S” at the end of this person’s name. So, I think it is the same person, but I am not 100 percent sure. The person who was friends with Thomas Jefferson and inherited the plantation was Edward Coles. It is an interesting story, and has influenced our family for many generations.

Following the story of the adoption of the thirteenth amendment to the Constitution to outlaw slavery, Steven Spielberg’s movie Lincoln deals primarily with the passing of this Amendment. It is interesting to see which party has been against slavery since its formation and most members I know in that party are for guaranteeing that all men (and women) have equal opportunity to succeed or fail. Again, the movie Lincoln is an excellent movie. The trailer is:

All men and women are created equal in the eyes of God, and we should treat others as precious children of God. Look for the positive qualities in others. Avoid untruths about others. Untruths serve no purpose except to tear the fabric of our country apart.

Paul McCartney

I recently saw a joyous video with Paul McCartney. I remember listening to the Beatles in High School. One of my best friends, Chuck Furbush, was a big Beatles fan. I remember when Sergeant Pepper’s Lonely Hearts Club Band came out, he was so excited to play it for me when I visited him at his uncle’s in Los Angeles. Lori Kristovich, who lived across the streetfrom me, also enjoyed listening to the Beatles. Ah the memories of high school. The video really shows the love Paul McCartney has for life and those around him. He is so kind to all those around him, that I am even more impressed with the person he has become even with all the fame he has achieved. May we all be so loving and caring towards others.

In some ways, it makes me feel old. In most ways, it makes me appreciate all the wonderful friends I have had and the people who have been so important to me. I know that there is no going back to the way it was in the past, that we must each build on our own experiences and the knowledge we have gained. I wish all my friends, past and present, all the love that God has in store for each of you. Enjoy reminiscing and enjoy living life to the fullest.

Chris Platt

I honestly did not think that I would be quoting something from the MTV Awards in this post, but I think it is a good way to conclude this post. I think Chris states it like he sees it, some a bit too descriptive, but overall I think what he has to say is important. I especially like rules 6, 8, and 9, and the reaction the audience has towards all the rules.

May God bless each of us and help each of us to be our very best. Treat each other as a child of God (originally typed Gold, and that may be just as true)created with the right to equal opportunities. Encourage all to be our very best.

Posted in Attitude, Becoming, Do, Fulfilling Life, older Americans, Self-Worth, Serving, Uncategorized | Tagged , , , , , , | 2 Comments

Be the Author of Your Own Life

We are the author of our own lives. How will we live to our fullest? None of us knows what is going to happen in the future. We may plan and we may have a good idea especially if we work towards certain goals. But there are risks we all take just by living our own lives. We depend on trusting others to do what is expected and to not have someone else’s sneeze cause us so much pain and suffering. But when something does happen, it is the measure of our souls in how we deal with that setback. Amy Purdy is a great example of overcoming such an unexpected problem. I hope none of us have to go through such learning experiences to know how important living life to the fullest is.

Amy has an amazing story. Anyone who can go through so much and still keep a positive attitude is an inspiration to me. My son, Matthew is also amazing. He has had five open heart surgeries in his young life, but enjoys life more than anyone else I know. I am looking for ways to bottle that love for life and share it with myself and with others. A few things I have learned recently include:

  1. Having a plan for each day. This includes an occasional plan to go off and do something totally unplanned. This is not a contradiction, because we all need to recharge our batteries,
  2. Learn something new each day. If it is not recorded someplace where it can be easily seen, it is not learned.
  3. Plan as if you will live forever, live as if today is your last day with the ones you love.
  4. Always ask “What have I done for others today?” You might be amazed, looking back at a month, all that you have accomplished in service.
  5. Live within your means. If your means do not match your actual needs, look for ways to legally increase you means.

Diana, Matthew, and I saw Amy Purdy do her presentation at a Convention a few years ago. We were impressed with her life story then. When Dora, a good friend, posted this video, it reminded my of what a dedicated person can do. Age is not a factor, mental attitude is. What do you want out of life and what are you going to do to obtain your dreams? As I grow, I will post what I learned each day here and add snippets of my dreams and plans here. I wish you all the best to live your dreams to your fullest.

18 June 2018 – My daily learning is to learn something new each day. My plans are to do well in my teaching position and complete my plans for the fall semester. Sometimes preparing for good services is just as important as the rendered service.

29 June 2018 – Procrastination is one of the biggest impediments to achieving anything worthwhile. As you can see, it is something I fight and is why there is such a gap in putting down what I have learned.

Posted in Attitude, Becoming, Do, Financial Health, Fulfilling Life, Goals, Health and Wellness, I Am, Mentor, Network Marketing, Planning, Self-Worth, Serving, Thinking | Tagged , , , , , , , , , , , , | 2 Comments