FAQ - Why does the output disappear?

Q1. Why does the output window disappear before I can see it?
A1.

Depending on the development system, the output window disappears when the program is finished running. There are two solutions:
1) Put system ("PAUSE") right before return 0;
     system ("PAUSE");
     return 0;
   }

2) In Microsoft Visual Studio, run without debugging Ctrl-F5

FAQ - Building a Visual Studio C program instead of C++

Q1. How do I get Visual Studio to build a C-language program instead of C++?
A1.

The precompiled headers option must be turned off and the file extension must be .c The 'precompile headers' option can be turned off either when the project is first being created or it can be turned off after the project is has already been created. The steps are different.

  1. When first creating the project, select New Project / Visual C++ / Win32 Console Application give the project a Name and click OK. When the next window appears, click the Next button. Unselect the Precompiled header check box and click Finish
  2. Make sure that the program is named with a .c file extension instead of .cpp Select VIEW / Solution Explorer and rename the file with a .c file extension
  3. Depending on which version of Visual Studio you have, you most likely will have references to either pch.h and pch.cpp -OR- stdafx.h and stdafx.cpp that refer to 'pre-compiled-header files'
  4. Delete the pch.h and pch.cpp -OR- stdafx.h and stdafx.cpp files from the list of files shown in the Solution Explorer
  5. Remove the #include pch.h -OR- stdafx.h line from the program
  6. Change the line with int _tmain to int main(int argc, char* argv)
Q2. You receive the following error when trying to build a C-language program on Microsoft Visual Studio: Precompiled header file is from a previous version of the compiler, or the precompiled header is C++ and you are using it from C
A2.

Turn off the precompiled headers for your project Select Not Using Precompiled Headers. Click OK

  1. Select PROJECT / Properties / Configuration Properties / C/C++ / Precompiled Headers
  2. Click the line Precompiled Header. Click the down-arrow on the right side
  3. Click OK

FAQ - My compiler gives an error message concerning  scanf_s

Q1. FAQ - My compiler gives an error message concerning  scanf_s
A1.

In the beginning… The C-language used scanf, but many C compilers consider the original version of scanf to be 'deprecated' or old-fashioned and have replaced scanf with scanf_s. The _s indicates this is a secure version of scanf. Some compilers still use scanf. If this is a case with your compiler, just replace scanf_s with scanf in the Rock-Paper-Scissors program.

Why use scanf_s? Buffer overrun can happen when using the original scanf. For example, if the programmer wants the user to input a name and creates an array that can hold 10 characters to receive the name, and the user inputs 20 characters, scanf would fill the array with the first 10 characters and then keep putting the rest of the characters on top of other data or program code and wipe out those memory locations. The scanf_s version requires the programmer to provide one more parameter when inputting a character string, the size of the array (buffer) that will be receiving input data. The scanf_s routine limits the number of characters input. This extra parameter is not needed when inputting a single character. In this case scanf and scanf_s are written with the same set of parameters. Parameters are the things inside the parentheses ( ).

FAQ - end1 error reported when building the program

Q1. Why does a C++ program report an error when typing end1?
A1.

The cout statement in C++ uses endl to end a line of text and move the cursor down to the next line. The word endl stands for End-Line. A common mistake for programmers new to the C++ language is to type end1 with the number-1 instead of endl, with the small-L.

Compare the difference in how the small-L and number-1 look with different fonts.
     Times New Roman l vs 1
     Courier l vs 1

Depending on the font you are looking at, the small-L and the number-1 look very similar. Actually, many of the older typewriters did not even have keys for the number-1 or number-0. Typists were instructed to use the small-L and capital-O instead. In the days of computers, the small-L and number-1 as well as the capital-O and number-0 are very different characters.

FAQ - COFF Error reported when building the program

Q1. How do I fix a COFF Error in Microsoft Visual Studio?
A1.
  1. In the 'Solution Explorer' window, click the name of your project
  2. From menu, choose <view><property pages>. The the property pages window should appear.
  3. From that window, choose <Linker><General>
  4. In 'Enable Incremental Linking', choose “No (/INCREMENTAL:NO)

FAQ – How do I download Xcode for macOS?

Q1. FAQ – How do I download Xcode for macOS?
A1.

NOTE: As of Feb 2020, the latest version of Xcode requires macOS 10.14.4 or later

1) Use Safari to go to https://developer.apple.com/xcode/
2) Click "Develop" at the top of the window
3) Login with your Apple Developer ID. If you don't have one, create one.
4) Scroll to the bottom. Click "Downloads" at the bottom of the screen
5) at the upper-right corner, click the link for "Release"
6) Click "View on the App Store"
7) Click the "Get" button

FAQ – Build a C++ program using Mac Xcode

Q1. How do I build a C++ program using Xcode?
A1.

Do not select 'Playground'.
1) Open Xcode
2) Select File / New / Project
3) Select OS X / Application / Command Line Tool --- Then click Next
4) Enter a Product Name ( such as paycheck ) / Set the Language to C++ --- Then click Next
5) Select a folder (such as Desktop) --- then click Create
6) Double-click main.cpp (on the left side of the screen)
7) Enter your program (don't enter the line #include "stdafx.h" - (only for Microsoft)
8) Run the program Product/Run or command-R

FAQ – Build a C program using Mac Xcode

Q1. How do I build a C program using Xcode?
A1.

Do not select 'Playground'.
1) Open Xcode
2) Select File / New / Project
3) Select OS X / Application / Command Line Tool --- Then click Next
4) Enter a Product Name ( such as paycheck ) / Set the Language to C++ --- Then click Next
5) Select a folder (such as Desktop) --- then click Create
6) Double-click main.cpp (on the left side of the screen)
7) Enter your program (don't enter the line #include "stdafx.h" - (only for Microsoft)
8) Run the program Product/Run or command-R

FAQ – Using scanf with %c

Q1. Why does the program ignore inputs when using scanf with %c?
A1.

Whitespace includes the space, tab, Enter and Return characters. Normally, scanf ignores leading whitespace characters, inputs the requested data and then stops when encountering a whitespace character leaving the whitespace character still in the input buffer. When reading a single character using scanf or scanf_s, place a space before the % character in "% c". However, if scanf(" %c", ... does not ignore leading whitespace characters. If it follows a previous call to scanf, scanf will receive the whitespace character left over from the previous scanf and does not input the desired character.

Solve this problem by calling flushall( ); before using scanf(" %c", ...

     flushall();                   /* clear the keyboard buffer */
     scanf (" %c", &Player1);       /* input for Player 1 */


If your compiler does not have the flushall() function, you can use this code

     int c;
     while ((c = getchar()) != '\n' && c != EOF);
     scanf (" %c", &Player1);       /* input for Player 1 */

FAQ – Inputting Single Characters in C and C++

Q1. Why is so hard to input a single character from the keyboard
A1.

Inputting a single character can be rather a problem with the more modern operating systems. They like to buffer the input and hold it until the Enter key is pressed. Different pieces of software have different ways of dealing with this when trying to input a single character. getch and getchar worked great with the old MS/DOS because our programs could bypass the operating system and work directly with the hardware. This is no longer the case. The operating systems place a barrier between application programs and the hardware.

Solution in C++
When using cin with C++ reading a single character is not too noticeable because cin ignores whitespace characters like space, tab and Enter. For example, the RockPaperScissors game the following code in C++

char player1, player2;

cout << "Enter player1 (R P or S): ";
cin >> player1;

cout << "Enter player2 (R P or S): ";
cin >> player2;

cin will ignore multiple space or tab keys and accept the next non-whitespace character and place it into player1, ignore multiple whitespace characters and then place the next character in player2. The cin routine only finishes executing when the Enter key is pressed AFTER a valid non-whitespace character is processed.

Solution in C
In the C-language, player1=getchar; and scanf("%c", &player1); will get the next character from the keyboard and place it in player1, but control does not return to the application program until the Enter key is pressed. What is unfortunate is that the Enter key is still sitting in the input buffer so that if this code is used,

char player1, player2;

printf ("Enter player1 (R P or S): ");
player1 = getchar(); // or scanf("%c", &player1); Visual C++ may require scanf_s
printf("Enter player2 (R P or S): ");
player2 = getchar(); // or scanf("%d", &player2);

We will read the desired character for player1, but when we try to read player2 both getchar or scanf will place the code for the Enter key in player2 and not even bother to read the character we were hoping for into player2. What we need to do is 'flush' the whitespace characters from the operating system's input buffer before using either getchar or scanf. this can be accomplished as:

printf ("Enter player1 (R P or S): ");
fflush (stdin);
player1 = getchar();
// repeat for player 2

// or using scanf

printf ("Enter player1 (R P or S): ");
scanf (" %c" &player1):
// repeat for player2

The " %c" in scanf has the space character before the %c to indicate to scanf to accept and ignore any leading whitespace characters.

If you write a C program in a project you created for C++ using either MSVC, Xcode, cpp.sh, etc. you will may also need    
fflush (stdout);     after each printf statement so that the the contents of the output buffer will be flushed to the screen. If you create the project for the C-language you should not need the fflush() after each printf statement.

FAQ – Extra credit

Q1. Are there extra credit points available?
A1.

Extra credit points count towards the number of points earned, but are not included in the total number of points for the class. For example, if the class has a total of 100 points for all assignments, quizzes and tests and you earned 85 points + 10 points for extra credit, your grade percentage would be (85+10)/100 = 95%. If you did not have the extra credit, your percentage would be (85)/100 = 85%.

Extra credit is available in two ways:
1) An extra credit assignment is like a regular assignment, and all of the points earned are counted as extra credit. The extra points are added into the total points received for the class but Canvas shows the assignment is worth 0 points of regular credit. For example if there were two regular assignments at 10 points each and one extra credit assignment and the student received 7 points each, the total percentage would be computed as follows: (7+7+7) / (10+10+0) = 21/20 = 105%
 
2) Sometimes a regular assignment may have extra credit for doing more than the minimum required to complete the assignment. For example a 10 point assignment may have the opportunity to earn an extra 3 points for a total of 13 points out of 10. The extra credit part of the assignment MUST be turned in when the assignment is submitted. The extra credit points will not be awarded at a later date even if the assignment is resubmitted. If an assignment is worth 10 points with 3 points extra credit, Canvas initially shows the assignment as 10 points. Extra credit points are added to the total score.

FAQ – How do I loop until a non-negative integer is input with cin?

Q1. How do I loop until a non-negative integer is input with cin?
A1.

A return statement inside of int main will cause the program to end. The value after the return (0 or 1) is only useful if the program is part of a chain of programs that are run one after another. A return value of 0 typically indicates that the program did not have a problem and other values are used to indicate an error or some other non-standard completion.
 
Assume that the following code is part of your program. The program will be terminated if either a non-integer or a negative value is input:
    if (cin.fail() || number < 1) //account for non integer and negative answers
    {
      cout << "Illegal entry" << endl;
      return 1; // kill the program
    }

If you want to have the program ask again if a negative number is entered, change the code to:
    if (cin.fail() || number < 1) //account for non integer and negative answers
    {
        cout << "Illegal entry" << endl;
        cout << "Enter a number: ";
        cin >> number; // ask for a new input
    }

So far, the code works if you enter a negative number, but still fails if you enter something illegal. Because the cin is expecting to input into an integer, anything that is left in the keyboard input buffer is left there and the next time in the loop that cin is called, the bad value is still there without you even getting a chance to type anything new. Here is the code updated to clear the input if it was illegal.
    if (cin.fail() || number < 1) //account for non integer and negative answers
    {
        cout << "Illegal entry" << endl;
        cout << "Enter a number: ";
        cin.clear(); // clear the input buffer
        cin.ignore(1000, '\n'); // and ignore anything else before a new cin
        cin >> number;
    }

The best update would be to change the if to a while so that the program keeps looping until an acceptable input is provided without going down and executing any code that follows.
    while (cin.fail() || number < 1) //reject non integer and negative answers
    {
        cout << "Illegal entry" << endl;
        cout << "Enter a number: ";
        cin.clear(); // clear the input buffer
        cin.ignore(1000, '\n'); // and ignore anything else before a new cin
        cin >> number;
    }

FAQ – How do I reject non-numeric or negative numbers with cin?

Q1. How do I reject non-numeric or negative numbers with cin?
A1.

// Reject non-numeric input and negative numbers
// This solution shows two examples on how to reject non-numeric and negative numbers
// 1) The first example shows how without using a try...throw...catch block
// 2) The second example shows how when using a try...throw...catch block


#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    int number1;
    int number2;

    ///////////// Example 1 -- not using a try...throw...catch block ///////////
    // Use cin.fail() to test for non-numeric input or a number less than zero
    cout << "Enter the first number: ";
    cin >> number1; if (cin.fail() || number1 < 0)
    {
        cout << "The first number entered was either non-numeric or less than zero" << endl;
        return 1; // kill the program
    }
    cout << "The first number " << number1 << " was greater than zero" << endl;

    ///////////// Example 2 -- using a try...throw...catch block ///////////
    // place the cin statement inside a try...throw...catch block
    try
    {
        cout << "Enter the second number: ";
        cin >> number2;
        if (cin.fail() || number2 < 0)
        {
            throw 1; // different values for the throw to display different conditions in the catch
        }
    }
    catch (int e)
    {
        cout << "The second number was either non-numeric or less than zero" << endl;
        return 1;
    }
    cout << "The second number " << number2 << " was greater than zero" << endl;
    return 0;
}

FAQ – Why Use a Structured Record

Q1. Why are structured records used to store the abbreviation and full name of each state?
A1.

A structured record can collect one or more data types into a single unit. Some languages refer to this as a Record, other languages such as C and C++ refer to it by the keyword struct. For example a record for a student might have several fields such as name, IDnumber, address, phone, e-mail, unitsTaken, GPA, etc. Since the record contains several data items grouped together, it is possible to pass the record from one part of the program to another part, or even have an array of many records, each having the same fields. An example definition for a student record might be:

    struct S_STUDENT {        // define a structured record
        char name[31];        // student name - limited to 30 characters + NULL byte
        int  ID;              // student ID number
        char address[51];     // address limited to 50 characters + NULL byte
        char state[3];        // 2-character state abbreviation + NULL byte
        char zip[11];         // ZIP+4 including the dash and NULL byte
        char email[101];      // email limited to 100 characters + NULL byte
        double unitsTaken;    // use double because some classes might be .5 units
        double gpa;           // GPA = grade point average
    };

In the Binary Search program, each record has a character array for the abbreviation of a state (3 bytes so that the end-of-string NULL byte can be included) and the full name of the state. A array of 50 records can hold the information for all 50 states, including their abbreviation and full name. The following code is doing two things at once. The typedef is creating a new data type called State. The data type is made of structured records struct S_STATE.

    typedef struct S_STATE {
        char Abbreviation[3];
        char StateName[15];
    } State;

The process could also be done in two steps. First, create the structured record, then create a new data type based on the structured record:

    struct S_STATE {                // define a structured record
        char Abbreviation[3];
        char StateName[15];
    };
 
    typedef S_STATE State;         // define a new data type called State. The new data type is built using the structured record S_STATE

FAQ – Comparing C-strings with strcmp, _strcmp, stricmp, _stricmp, strcasecmp

Q1. Why are there different functions that do string compare for C-strings
A1. The original version of the C-language had functions that could compare the contents of two strings. As the C and C++ languages evolved, it was determined that run-time errors could be caused when users input strings that were much longer than the program was expecting. Many of the compilers have deprecated (too old fashioned to be used) the strcmp function and have upgraded and renamed it to _strcmp. Some compilers upgraded strcmp but left its name to still be strcmp. Some compilers also upgraded the stricmp function and renamed it _stricmp while other compilers totally renamed it to strcasecmp.

strcmp compares two strings and returns a negative value if the strings do not match and string1 has a lower value than string2. A positive value is returned if string1 has a greater value than string 2. A zero is retuned if both strings are equal.

The stricmp function compares strings similar to strcmp but the case of the characters in the two strings are ignored. For example. big-A is treated the same as little-a.

The way these routines work is by comparing the strings character by character and subtracting the numeric value of a character in string1 from the numeric value character in string2. If there is a mismatch along the way, the routine returns a positive or negative number based on the difference of the first mismatch of the two strings. For example, 'C'-'F' results in -3, but 'F'-'C' is a +3. If they are the same, the result is zero and the function moves to the next character. If all of the characters match then the function returns a zero. In this way, these routines can be used to determine if the strings are equal or one of the strings has a higher or lower value. For example, these routines can be used when strings need to be sorted.

C++ now has a string data type. C++ strings can be compared using the >, the < and the == operators.

FAQ – Why is gets( ) deprecated?

Q1. Why is gets( ) deprecated?
A1. The gets( ) function is being deprecated by several compilers because it does not have a limit on the number of characters that can be input from the keyboard which can create problems if the user enters more characters that the size of the receiving array could hold. It is best to use fgets which was originally created to get data from a file. Since the keyboard is being treated as a file named stdin by the operating system, fgets (buff, Buff_Size, stdin); is better and works in all cases instead of gets (buff, Buff_Size);

FAQ – C++ What is ----using namespace std;

Q1. C++ What is ----using namespace std;
A1. Originally, C++ did not use namespaces. As the language grew, it started being used for very large projects with several hundreds of programmers contributing to a single program. Programmers in completely different departments, sometimes in different buildings, started using completely unrelated variables and constants that happened to have the same names that were used by other people they didn't even know or work with. The idea of a namespace was created. Everything one group did was placed in one namespace, everything a different group did was placed in their own namespace.

The standard C++ functions are placed in the standard namespace, called std. Actually, you can get by without using namespace std;
in your program, but then you need to use the scope resolution operator ::
      std::cout << "Hello" << std::endl;
instead of
      cout << "Hello" << endl;

Some textbooks start having students use the   std::cout  in the first few chapters. It is just easier to place   using namespace std;  at the top of the program.

FAQ – C++ Rational Numbers Lab Assignment

Q1. Why change the sign on the numerator and denominator if the denominator is negative?
A1.

It just looks better when displaying a rational number with a positive denominator
   a) 2/3 not -2/-3
   b) -2/3 not 2/-3

Q2. Can the remainder be negative when dividing two integers?
A2. Yes. The remainder when dividing two numbers can be negative. For example -5 % 3 gives a remainder of -2
Q3. How is the equality operator == supposed to work?
A3. The return data type for the equality operator == should be bool (true or false). If the numerators of both numbers are the same, AND the denominators of both numbers are the same, then the two numbers are equal, so the == operator should return a true. Otherwise, return false.

FAQ – C++ Movie Rating Assignment Hints

Q1. How should the Movie Ratings assignment work?
A1. Without giving away all of the code for the Movie Ratings project, below is a sample of the main program.
int main(int argc, char *argv[])
{
   // Create two objects from the MovieRating class definition
   MovieRating Spiderman ("Spiderman
", "PG-13");
   MovieRating KillerTomatoes ("Attack of the Killer Tomatoes",
"PG");

   // Add several ratings for each movie
   Spiderman.rating(5);
   Spiderman.rating(4);
   KillerTomatoes.rating(3);
   Spiderman.rating(5);
   KillerTomatoes.rating(2);
   Spiderman.rating(5);

   // Display the results of several customer ratings
   cout << Spiderman.name( ) << " is rated " << Spiderman.MPAA( )
        << " It received" << Spiderman.stars( ) << " stars."endl;
   cout << KillerTomatoes.name( ) << " is rated " << KillerTomatoes.MPAA( )
        << " It received" << KillerTomatoes.stars(    ) << " stars."endl;


     return 0;
}

With the above code, the output should be:
Spiderman is rated PG-13. It received 4.75 stars.
Attack of the Killer Tomatoes is rated PG. It received 2.5 stars
.


The definition of the MovieRating class needs

   
     a) a constructor with two const char* arguments that get stored into private data
     b) when the rating member function is called, it needs to add the user's rating to a total and keep track of the count of the user ratings
     c) Accessor functions for name, MPAA and stars. The stars function should return a double that is the total / count.
In the above example, the total for Spiderman was 5+4+5+5=19 and the rating function was called 4 times. Therefore, 19/4 = 4.75 stars.

FAQ – C scanf Error Handling

Q1. How do I implement error handling in C when using scanf in the Electric Bill?
A1.

The Electric Bill assignment states that exception handling is to be used to reject non-numeric and negative inputs.

scanf attempts to read the input made of characters, convert and store them in the variables passed to scanf. For example
  result = scanf ("%d %d", &number1, &number2);
If the keyboard inputs are 20 and 30, scanf will store 20 in number1 and 30 in number2 and a 2 into variable result because scanf was successful in reading the input, converting it into two decimal values and storing them in memory. However, if the keyboard inputs are 20 and the letter 'x', scanf will only be successful in storing the value 20 in number1. scanf will not be able to convert the letter 'x' into a decimal value and will return a 1 into the variable result indicating that only one of its requests were satisfied. It is the programmer's responsibility to know how many conversions are being requested of scanf and check to make sure that the expected value matches the return value from scanf.

See below to implement the solution.

    double kWh;

    /* User input */
    printf ("Enter the amount of kWh used: "); /* prompt for an input from the user */
    /* scanf returns the number of items successfully processed */
    int itemsProcessed = scanf("%lf", &kWh); /* NOTE: some compilers may need scanf_s */

    /* check for scanf errors */
    if (itemsProcessed != 1) /* Was scanf able to store into a double? */
    {
        printf ("Unrecognized input\n");
        return(1); /* quit the program */
    }

    /* check for negative inputs */
    if (kWh < 0)
    {
        printf ("kWh must be a positive value\n");
        return(1); /* quit the program */
    }

    /* You need to write the code to calculate and display the bill */

FAQ – C++ Exception Handling

Q1. How do I implement Exception Handling in C++ (Try...Throw...Catch) in the Electric Bill?
A1.

The Electric Bill assignment states that exception handling is to be used to reject non-numeric and negative inputs. Use Try...Throw...Catch blocks as shown below to implement the solution.

    double kWh;
    // User input
    cout << "Enter the amount of kWh used: ";
    cin >> kWh;
 
    // Exception handling
    try
    {
        if (!cin) // Was cin able to store into a double?
            throw 0;  // Throw the error ID
        if (kWh < 0)
            throw 0;  // Throw the error ID
 
        // Calculate and display the bill while in the Try block
        // ..
.

    } //End of the try block
 
    catch (int errID)
    {
        cout << "Error: " << errID << endl;
        cout << "kWh must be a positive number" << endl;
    } //End of the catch block

FAQ – Can a constructor return an error?

Q1. Can a constructor return an error?
A1.

A constructor has no return value, but if an error is detected, use the throw command so that the error can be processed by the main program. For sample code see:

http://program-info.net/C++/downloads/C++ObjectsAndClasses/ConstructorThrowsError.cpp.txt

FAQ – How do you select a file named Balances on the Desktop?

Q1. How do you select a file named Balances on the Desktop?
A1.

To open a file, you must specify the full pathname and filename. This is called the fully-qualified filename. For example, when in C or C++, to open a file named Balances.txt that is located on the desktop, the fully-qualified filename on my system would be:
     /Users/Dan/Desktop/Balances.txt

The pathname consists of your HOME directory and /Desktop which is a folder on the operating system that
refers to the desktop. For example, my HOME directory is located at /Users/Dan
My desktop is located at    /Users/Dan/Desktop    This is true for either a Mac or PC.

Mac - To display the location of the HOME directory on a Mac running OS/X
1) Go to Launchpad and launch Terminal
2) at the Terminal prompt, type    echo $HOME
3) use this information followed by   /Desktop/Balances.txt   as the fully-qualified filename

Windows - To display the location of the HOME directory on a PC running Windows
1) click the START button on Windows located at the lower-left side of the screen
2) when the box pops up at the bottom that says, "Search programs and files", type   cmd  and press [Enter]
3) at the command prompt, type:    echo %UserProfile% 
4) use this information followed by   /Desktop/Balances.txt   as the fully-qualified filename

SPECIAL NOTE FOR PROGRAMMERS ON WINDOWS SYSTEMS
Windows uses the backslash character \ to separate parts of the pathname and filename.The C programming language was created to create the Unix operating system which uses the forward slash character / to separate the parts of the pathname and filename.

C and C++ use the backslash \ in character strings as an escape to give a new meaning to the next character. For example, \n is new line, \b is backspace, \t is tab, etc. It is necessary to type two backslashes \\ inside of a quoted string to get one backslash \ in memory. For example to get this:
   \Users\Dan\Desktop
The quoted string in a C or C++ program must be written as:
  "\\Users\\Dan\\Desktop"

Since web servers were originally developed on Unix systems, the forward slash / is used in web addresses. To make Windows compatible with the rest of the world, Windows now accepts forward slashes / as well as backslashes \ as part of a filename. In C or C++ you can now use
  "/Users/Dan/Desktop"
as well as
  "\\Users\\Dan\\Desktop"
to get the same result when refering to a file.

FAQ – What is XAML or Microsoft 'Blend'?

Q1. What is XAML or Microsoft 'Blend'?
A1.

If you see an error message that contains XAML when trying to write a C++ program using Microsoft Visual Studio, it appears that you are running "Microsoft Blend for Visual Studio" instead of Visual Studio itself. I suggest that you get out of this project and reopen Visual Studio. Make sure that you do not select the "Blend" option. When you get back into Visual Studio, Select New Project, then Visual C++, then Win32 Console Application.

"Extensible Application Markup Language, or XAML (pronounced "zammel"), is an XML-based markup language developed by Microsoft. XAML is the language behind the visual presentation of an application that you develop in Microsoft Expression Blend, just as HTML is the language behind the visual presentation of a Web page. Creating an application in Expression Blend means writing XAML code, either by hand or visually by working in the Design view of Expression Blend." (the quoted text is from the Microsoft Developer Network MSDN)

For more on XAML and Microsoft Expression Blend, see
https://msdn.microsoft.com/en-us/library/cc295302.aspx

FAQ – What are argc and argv used for on the int main line?

Q1. What are argc and argv used for on the int main line?
A1.

A C or C++ program can be part of a larger group of programs that are run one after another on the computer. One program can pass data to the next program with an argument list of values that are stored in an array of strings named argv. The argc parameter is is the count of arguments. If the program is run from the command line instead of the development system, then the program can receive the list of arguments from the command line. For example:
   copy abc xyz
is a DOS command that will copy the contents of abc into xyz.    argc is set to 3 and the arguments will be the three things that are on the command line, including the name of the program.

There is also an additional parameter that can be provided in int main and that is char *envp[] which is a list of the operating systems parameters.

You can write a C or C++ program with just int main( ) if you don't need to access the argument list. But since most C and C++ programs start with int main (int argc, char *argv[]) I usually just leave it there even if it is not used.

Microsoft likes to be special and uses _tmain and _TCHAR* which it then redefines to main and char * in case they want to change things for themselves in the future.

FAQ - How do you convert the row and seat selection to an array index?

Q1. How do you convert the row and seat selection to an array index?
A1.

The row and seat selection has two parts, the numeric row selection (1 to maxRow) and the alpha seat selection (A to Z). The program can input the row number either as a character into a char data type, or as an integer into an int data type. The seat selection must be input into a character data type.
Look at your program to see if the row and seat selections were input into char or int data types.

Arrays start their index at 0 and must be integers. Therefore row and seat values input from the keyboard need to be converted to integers, starting at 0.
If the row was input as an integer, then subtract 1 so that the array index will start at 0. For example, if the user typed a 5 and the program read it as an integer, the row index would be converted to a 4 for the array (5 - 1 ===> 4).

However, if the row was input into a character data type, then subtract a character literal '1'. Refer to the ASCII chart at http://program-info.net/C++/ascii.htm and you will see that a character '1' has a decimal value of 49. Therefore, if the user typed a '5' and the program read it as a character, the row index would be converted to an integer 4 for the array ('5' - '1' ===> 4). When looking at the character code decimal values for '5' and '1', (53 - 49 ===> 4).

A similar procedure happens with the seat. But since it must be input as a character, we just need to convert it to an integer value for the array index, starting at 0. The seats start a 'A' which needs to be converted to starting from 0 for the array index. Therefore, just subtract the character literal 'A'. For example, if 'D' was input for the seat, then 'D' - 'A' would be 3, or looking at the ASCII table for the decimal values of 'D' and 'A' (68 - 65 ===> 3).

FAQ - Reserved Seats

Q1. How do you identify a seat being taken using '-'?
A1.

Assuming that you have a two dimensional array named ArrayOfSeats, you can use the code shown below. You still need to verify that a valid row and seat were entered by the user.


int rowSelection;   // 1 to max NumberOfRows, input from the user
char seatSelection; // 'A' to max seats, input from the user, convert to a number
int row;            // index into ArrayOfSeats, 0 to NumberOfRows-1
int seat;           // index into ArrayOfSeats, 0 to seats-1

cout << "Enter a seat selection (example 5F): ";
cin >> rowSelection;   // get row from the user
cin >> seatSelection;  // get the seat from the user
seatSelection = toupper(seatSelection); // convert to upper case
row = rowSelection - 1; // count from zero to work with the array
seat = seatSelection - 'A'; // convert 'A' to 0, 'B' to 1, 'C' to 2, etc.

// Verify that a valid row and seat were entered
// See if all the seats are taken
// hint, keep a count each time a seat is taken
// and compare to the maximum number of seats (NumberOfRows*seats)
// See if the seat selection is already taken (see if it has an '-')
// if it has an '-', display a message that the seat is taken
// else, put an '-' in that location

if (ArrayOfSeats[row][seat] == '-')
  cout << "The seat you selected has already been taken." << endl;
else
  ArrayOfSeats[row][seat] = '-';

FAQ - Mean and Median of a Disk File

Q1. Do you have any hints on finding the mean and median of a disk file?
A1.
  1. Run the program two different times. Once for Balances-1.txt and the second time for Balances-2.txt. Don't try to open both files at the same time (unless you want to super complicate the program).
  2. You can either define   ifstream infile;    with no filename and then later get the filename from the user, or you can define infile with a filename. Don't do both in the same program.
    ifstream infile("/Users/Dan/Desktop/Balances-1.txt");
  3. I provided the code to determine the number of records to skip to find the median value. In part-3, open the file again and start reading records until you have reached the one that contains the median. You don't need to do anything with the data in these skipped records. When you have reached the record that is the median, display it. This works fine if you have an odd number of records in the file. If the number of records is even, you need to read two records adding up the values AcctBal in both records and dividing by 2. That will give you the median value.
  4. The lab assignment is also asking you to find the mean, also known as the common average. Most of the code is already in Part-1 of the program. Part-1 already reads every record in the file. Set up a separate double variable total and initialize it to a zero at the top of the program. As you read each record in Part-1, add the AcctBal to the total. The mean is going to be the total divided by the recordCount.
  5. Sample code for Part-3
   while (!infile.eof() && recordsToSkip--) // <===== while not end of file, count down to find the median
   {
      Name[0] = 0; // initialize to 0 to test for empty records/
      infile >> AcctNo >> Name >> AcctBal; // don't do anything with these records, just read them to get to the median record
      if (Name[0] != 0) // ignore empty records
         recordCount++;
   }
   infile >> AcctNo >> Name >> AcctBal; // <=========    read the median record
   median = AcctBal; // <=== we have skipped down to the median value

FAQ – How do I start implementing the standard deductions?

Q1. How do I start implementing the standard deductions?
A1. Let's start with selecting the choice between itemized and standard.
   cin >> choice;  // where choice is of type char
   if (choice == 'I') // compare to the character capital-I, not the variable I

You need to compare to a 'I', not a variable named I. It would be even better to accept both big and small i
   if (choice == 'I' || choice == 'i') // compare to the character capital or small I

For standard deductions, we need to look up a value in the array, based on the tax status, which is passed into the function as int s. Because an array index (position) starts at 0, we do need to subtract 1 from the taxpayer status in order to select the correct location in the array. NOTE: we need to subtract 1, not the code for the printable character '1', which would actually subtract 49. Refer to the numeric values of character codes at http://program-info.net/C++/ascii.htm

Here is the code that would get the correct value for standard deductions.
   else
   {
      i = taxpayerStatus - 1;     // where i will be used as the index
      deductions = standardDeductionTable[i]; // look up from the table
   }
   return deductions; // can be either itemized or standard
} // end of the function inputDeductions

FAQ – Hints for the Roll Dice Histogram Using Individual Counters?

Q1. Hints for the Roll Dice Histogram Using In?
A1.

Two functions are needed when using the random number generator in C or C++. The rand( ) function produces random numbers based on its own internal formula.

The srand() function is only used one time, typically at the beginning of the program. It 'seeds' the random number generator so that it does not produce the exact same sequence of numbers every time the program is run. Start the program with int main, then call the srand( ) function. To make sure it is only called one time, do not put the srand( ) function in a loop. The code for the roll( ) function also shows another way to seed the random number generator, and only do it one time.

int main( )
{
srand (time(0)); // Seed the random number generator - one time only

You can either use a collection of separate counters or an array to keep track of each time a pair of numbers occurs when rolling the dice. A seprate FAQ describes how to use an array for the counters.

// declare counters for counts two through twelve before the for loop
int two = 0;
int three = 0; // declare more counters, up through int twelve

Use a loop to roll a pair of dice 1000 times to get the value of 2-12 for each roll

for (int i=0; i<1000; i++) {
    int roll1 = roll(); // code for roll() is on the project description PPT
    int roll2 = roll(); // roll the second die
    int rollResult = roll1 + roll2;

Now you can use the switch and case statements to increment the counters

switch(rollResult){
case 2:
    two++; // if the count is 2, increment the counter named two
    break;
case 3:
    three++; // if the count is 3, increment the counter named three
    break;
// continue this sequence for combinations up to 12

   } // end of switch/case block

} // end of for loop


Finally, display the results and then end the program

    // write code to display the counters

} // end of main( )

FAQ – Hints for the Roll Dice Histogram Using an Array?

Q1. Hints for the Roll Dice Histogram Using an Array?
A1.

Two functions are needed when using the random number generator in C or C++. The rand( ) function produces random numbers based on its own internal formula.

The srand() function is only used one time, typically at the beginning of the program. It 'seeds' the random number generator so that it does not produce the exact same sequence of numbers every time the program is run. Start the program with int main, then call the srand( ) function. To make sure it is only called one time, do not put the srand( ) function in a loop. The code for the roll( ) function also shows another way to seed the random number generator, and only do it one time.

int main( )
{
srand (time(0)); // Seed the random number generator - one time only

You can either use a collection of separate counters or an array to keep track of each time a pair of numbers occurs when rolling the dice. A separate FAQ describes how to use separate counters.

// use an array of 13 integers. Ignore positions 0 1, initialize all zero
int histogram[13] = {0};

Use a loop to roll a pair of dice 1000 times to get the value of 2-12 for each roll

for (int i=0; i<1000; i++) {
    int roll1 = roll(); // code for roll() is on the project description PPT
    int roll2 = roll(); // roll the second die
    int rollResult = roll1 + roll2;

Now you can use the switch and case statements to increment the counters

////// use the array instead inside the for loop
histogram[rollResult]++; // increment counter for result of rolling 2 dice

} // end of for loop


Finally, display the results and then end the program

    // write code to display the counters

} // end of main( )

   

FAQ – How do I use the screen magnifier on Windows or macOS?

Q1. How do I use the screen magnifier on Windows or macOS
A1.

The Windows Magnifier tool can be used on any part of the screen. To activate the magnifier

click the Windows menu on the lower-left of the screen
click the gear-icon to select "Settings"
click the "Ease of Access" tool
set the Magnifier to ON

You can activate the magnifier with the "Windows" key and the "+" key
Turn off the magnifier with the "Windows" key and the "Esc" key

On a Mac and running macOS, the magnifier/Zoom tool is activated by

click the Apple icon at the upper-left of the screen
select "System Preferences"
click "Accessibility
make sure the "Zoom" shortcut is clicked in the right window pane
click Zoom in the left window pane
click the "Use keyboard shortcuts to zoom

You can activate/disable Zoom with the Option+Command+8 keys
Increase zoom with Option+Command+EqualKey (=)
Decrease zoom with Option+Command+MinusKey (-)