Basic learning of C language -- C Primer Plus

C Primer Plus programming exercises - Chapter 8 - character input / output and input verification

C Primer Plus 8.11
First question of programming practice

/* C Primer Plus 8.11 - The first question of programming practice  */

/* Title: design a program to count the number of characters read before the end of the file */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  int ch, i = 0;
  FILE *fp;
  char fname[50];

  printf("Enter the name of the file: ");
  scanf("%s", fname);               // Enter file name, file path required
  fp = fopen(fname, "r");           // Open as read-only
  if (fp == NULL){
    printf("Failed to open file.\n");
    exit(1);
  }

  while ((ch = getc(fp)) != EOF){    // End of file stop
    putchar(ch);
    i++;      // Read character, add 1
  }

  fclose(fp);         // Close file
  printf("\nThe file has %d byte", i);

  getchar();
  getchar();
  return 0;
}
// C:\Users\SieYuan\Desktop\test8.11-1.txt

Programming exercise 2

/* C Primer Plus 8.11 - The second question of programming practice  */

/* Title: write a program to read the input as a character stream before encountering EOF.
The program will print each input character and its corresponding ASC Ⅱ decimal value. */
#include <stdio.h>
int main(void)
{
  int i = 0, ch;

  while ((ch = getchar()) != EOF){
    i++;
    if (ch == '\n'){
      putchar('\\');
      putchar('n');
      printf(" %d\n", ch);
      i = 0;
    }
    else if (ch == '\t'){
      putchar('\\');
      putchar('t');
      printf(" %d\t", ch);
    }
    else if (ch < ' '){
      putchar('^');
      putchar(ch + 64);
      printf(" %d\t", ch);
    }
    else{
      printf("%c %d\t", ch, ch);
    }
    if (i == 9){
      putchar('\n');
      i = 0;
    }
  }
  getchar();
  return 0;
}

The third problem of programming practice

/* C Primer Plus 8.11 - The third problem of programming practice  */

/* Title: write a program to read the input as a character stream before encountering EOF.
The program reports the number of uppercase and lowercase letters in the input. Assumed case letters
 The values are continuous. Or it is more convenient to use the appropriate classification function in ctype.h library. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  int capital = 0, lower = 0;
  int ch;

  printf("Enter a string and # to quit: ");
  while ((ch = getchar()) != EOF && ch != '#'){
    if (ch >= 'A' && ch <= 'Z')
      capital++;
    else if (ch >= 'a' && ch <= 'z')
      lower++;
  }
  printf("Capital letters: %d, Lower case letter: %d\n", capital, lower);

  system("pause");
  return 0;
}

Programming exercise 4

/* C Primer Plus 8.11 - Programming exercise 4  */

/* Title: write a program to read the input as a character stream before encountering EOF.
The program reports the average number of letters per word. Don't count blanks as letters of words.
In fact, punctuation should not be counted. Consider using the ispunct() function in the ctype.h series  */
#include <stdio.h>
#include <ctype.h>    // ispunct() checks whether the character is a punctuation mark, true, false
#include <stdbool.h>
#include <stdlib.h>
int main(void)
{
  int ch, ch_bf;
  int word = 0;       //Number of words
  int word_ch = 0;    //The number of letters in a word

  printf("Enter a string and # to quit: ");
  while ((ch = getchar()) != EOF && ch != '#'){
    if (ch == ' ' || ispunct(ch) == true)
      word++;
    else
    {   
      if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')
      // &&It is higher than|, so it is not bracketed
        word_ch++;
    }
    ch_bf = ch;
  }
  if (ch_bf == ' ' && ch == '#')
    printf("The number of words: %d\nAverage letters per word: %.2f\n",
    		 word, (float) word_ch / word);
  else
    printf("The number of words: %d\nAverage letters per word: %.2f\n", 
    		word + 1, (float) word_ch / (word + 1));

  system("pause");
  return 0;
}

Programming exercise 5

/* C Primer Plus 8.11 - Programming exercise 5  */

/* Title: modify the guessing program in listing 8.4 to use a more intelligent guessing strategy.
Use binary search strategy. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  int guess = 50;
  char response;
  int min = 1;
  int max = 100;

  printf("Pick an integer from 1 to 100. I will try to guess it\n");
  printf("Respond: y - yes, s - small, b - big.\n");
  printf("Uh... is your number %d?\n", guess);
  while ((response = getchar()) != 'y'){
    if (response == 'b'){
      max = guess;
      guess = (max + min) / 2;
      printf("Well, then, is it %d?\n", guess);
    }
    else if (response == 's'){
      min = guess;
      guess = (max + min) / 2;
      printf("Well, then, is it %d?\n", guess);
    }
    else{
      printf("Sorry, I understand only y or s or b.\n");
    }
    while (getchar() != '\n')
      continue;
  }
  printf("I knew I could do it!\n");

  system("pause");
  return 0;
}

Programming exercise 6

/* C Primer Plus 8.11 - Programming exercise 6  */

/* Title: modify the get first() function in listing 8.8 to return the first one read
 Non whitespace characters and tested in a simple program. */
#include <stdio.h>
#include <stdlib.h>   // exit()
#include <ctype.h>
char get_first(FILE *fp);
int main(void)
{
  int ch;
  char fname[50];
  FILE *fp;

  printf("Enter the name of the file: ");
  scanf("%s", fname);
  fp = fopen(fname, "r");     // Open file to read
  ch = get_first(fp);
  printf("first char: %c\n", ch);
  fclose(fp);       //Close file
  system("pause");
  return 0;
}
char get_first(FILE *fp)
{
  char c;

  while ((c = getc(fp)) == ' ')
    continue;
  return c;
}

Programming exercise 7

/* C Primer Plus 8.11 - Programming exercise 7  */

/* Title: revise 7.12-8 of Chapter 7 to mark the menu with characters instead of numbers.
Use q instead of 5 as a marker to end the input. */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define WAGE_LEVEL1 8.75
#define WAGE_LEVEL2 9.33
#define WAGE_LEVEL3 10.00
#define WAGE_LEVEL4 11.20
#define OVERTIME 40.0
#define RATE_300 0.15
#define RATE_150 0.20
#define RATE_rest 0.25
void display(void);
float work_time(int level);
float taxrate(float sum);
int main(void)
{ 
  char button;
  float worktime;
  float tax, wage_hr;
  float salary, aft_salary;  // after-tax salary;

  display();

  while ((button = getchar()) != EOF && button != 'q'){
    while (button != '\n'){
      switch (button){
        case 'a': worktime = work_time(1);
                wage_hr = WAGE_LEVEL1;
                salary = wage_hr * worktime;
                tax = taxrate(salary);
                aft_salary = salary - tax;
                break;
        case 'b': worktime = work_time(2);
                wage_hr = WAGE_LEVEL2;
                salary = wage_hr * worktime;
                tax = taxrate(salary);
                aft_salary = salary - tax;
                break;
        case 'c': worktime = work_time(3);
                wage_hr = WAGE_LEVEL3;
                salary = wage_hr * worktime;
                tax = taxrate(salary);
                aft_salary = salary - tax;
                break;
        case 'd': worktime = work_time(4);
                wage_hr = WAGE_LEVEL4;
                salary = wage_hr * worktime;
                tax = taxrate(salary);
                aft_salary = salary - tax;
                break;
        default:printf("Error! Retry!\n");
                break;
      }
      printf("Hourly pay:%.2f dollar/hour\n Total working hours of the week: %6.2f hour\n Wages payable: %6.2f dollar\n"
      "tax    gold: %6.2f dollar\n Real wages: %6.2f dollar\n\n", 
      wage_hr, worktime, salary, tax, aft_salary);
      worktime = salary = tax = aft_salary = 0.0;
      display();
      button = '\n';
    }
  }
  printf("Quit!");
  system("pause");
  return 0;
}
void display(void)
{
  int i;
  for(i = 0; i < 65; i++)
    printf("%c",'*');
  printf("\nEnter the number corresponding to the desired pay rate or action:\n");
  printf("a) $8.75/hr                           b) $9.33/hr\n");
  printf("c) $10.00/hr                          d) $11.20/hr\n");
  printf("q) quit\n");
  for(i = 0; i < 65; i++)
    printf("%c",'*');
  printf("\n");
}
float work_time(int level)
{
  float t;
  printf("You choose level %d hourly wage!\nEnter your worktime in a week (hr): ", 
  level);
  scanf("%f", &t);
  if (t > 40.0)
    t = 40.0 + (t - 40.0) * 1.5;
  return t;
}
float taxrate(float sum)
{
  float tax_;
  if (sum <= 300.0)
    tax_ = RATE_300 * sum;
  else if (sum > 300.0 && sum <= 150.0)
    tax_ = 300.0 * RATE_300 + (sum - 300.0) * RATE_150;
  else
    tax_ = 300.0 * RATE_300 + 150.0 * RATE_150 + (sum - 450.0) * RATE_rest;
  return tax_;
}

Programming exercise 8

/* C Primer Plus 8.11 - Programming exercise 8  */

/* Title: write a program to display a menu of addition, subtraction, multiplication and division. Get users
 After selecting the option, the program prompts the user to enter two numbers, and then performs the operation that the user just selected. The program
 Accept only the options provided by the menu. The program uses float type variables to store the number entered by the user, if the user
 If the input fails, it is allowed to input again. When performing division operation, if the user enters 0 as the divisor, the program shall provide
 Show the user and re-enter a new value. An example is as follows: */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void display(void);
int op_add(void);
int op_sub(void);
int op_muti(void);
float op_div(void);
int input_first(void);
int input_second(void);
int main(void)
{ 
  char button;

  display();

  while ((button = getchar()) != EOF && button != 'q'){
    while (button != '\n'){
      switch (button){
        case 'a': op_add();
                  break;
        case 's': op_sub();
                  break;
        case 'm': op_muti(); 
                  break;
        case 'd': op_div();
                  break;
        default:  printf("Error! Retry!\n");
                  break;
      }
      display();
      button = '\n';
    }
  }
  printf("Quit!");
  system("pause");
  return 0;
}
void display(void)
{
  int i;
  for(i = 0; i < 65; i++)
    printf("%c",'*');
  printf("\nEnter the number corresponding to the desired pay rate or action:\n");
  printf("a) add                            s) substract\n");
  printf("m) mutiply                        d) divide\n");
  printf("q) quit\n");
  for(i = 0; i < 65; i++)
    printf("%c",'*');
  printf("\n");
}

int op_add(void)
{
  int first, second, res;

  first = input_first();
  second = input_second();
  res = first + second;
  printf(" %d + %d = %d\n", first, second, res);
}
int op_sub(void)
{
  int first, second, res;
  first = input_first();
  second = input_second();
  res = first - second;
  printf(" %d - %d = %d\n", first, second, res);
}
int op_muti(void)
{
  int first, second, res;
  first = input_first();
  second = input_second();
  res = first * second;
  printf(" %d × %d = %d\n", first, second, res);
}
float op_div(void)
{
  int first, second;
  float res;
  first = input_first();
  second = input_second();
  while (second == 0.0){
    printf("Error!");
    second = input_second();
  }
  res = ((float)first) / ((float)second);
  //printf("%d,%f\n\n", (int)res, res);
  if (res == (int)res)
    printf(" %d ÷ %d = %d\n", first, second, (int)res);
  else
    printf(" %d ÷ %d = %.3f\n", first, second, res);
}
int input_first(void)
{
  int i1;
  printf("Please input the first integer: \n");
  while ((scanf("%d", &i1)) == 0){
    printf("Error, retry!");
  }
  return i1;
}
int input_second(void)
{
  int i2;
  printf("Please input the second integer: \n");
  while ((scanf("%d", &i2)) == 0){
    printf("Error, retry!");
  }
  return i2;
}

Published 7 original articles, won praise 4, visited 183
Private letter follow

Tags: Programming

Posted on Fri, 07 Feb 2020 11:14:27 -0500 by davieboy