The Lecture for Turbo C

Post on 14-Nov-2014

124 views 0 download

Tags:

description

This is a set of slides I used for communicating with my classmates about Course Programming Fundermental

Transcript of The Lecture for Turbo C

The Lecture forTurbo C

David Van SchumacherBUPT-QM 07B05

Friday, December 28, 2007

STRINGS FUNCTIONSSection A

Fundamental functions

• Input–scanf–getchar–gets

• Output–printf–putchar–puts

Grammar

• scanf(“input format”,&variety name);• gets(variety name);• variety name = getchar();

What’s string in turbo C

• It’s NOT a string anymore.• It is seemed as a series of characters, which is

a character array.• The number of the character array is just the

same as the number of letters of the word or sentence plus one.

• The one more element is “\0” which is printed as “\n” by gets and printed as “”(NULL) by other words.

Library Functions<string.h>

• strcat(string1,string2)– Appends string2 to the end of string1– Usage: Create the name of data file.

• strlen(string)– Returns the length of string. Doesn’t include the “\

0”!!!!!!!!!– Usage: Determine whether a input data is valid for

your program.

Library Functions<string.h>

• strcpy(string1,string2)– Copies string2 to string1, including the “\0”

• strncpy(string1,string2,n)– Copies at most n characters of string2 to string1. If

string2 has fewer than n characters, it pads string1 with “\0”s.

– Usage: Used for Create a short file name if a string is too long.

Library Functions<string.h>

• strcmp(string1,string2)– Compares string1 to string2. Returns a negative

integer if string1<string2. 0 if string1==string2. positive integer if string1>string2.

• strncmp(string1,string2,n)– Compares the first n letters of string1 and string2

return the value as function “strcmp”.• Usage: We can use it for comparing if your

program work properly when you call some data file.

Library Functions<ctype.h>

• isalpha (determine whether is it a letter)• isupper (determine whether is it uppercase)• islower (determine whether is it lowercase)• isdigit (determine whether is it a number)• ispunct (determine whether is it a punctuation)• toupper (change lowercase to uppercase)• tolower (change uppercase to lowercase)

• Format: Function name(character variety name)• True ----- !0 False ----- 0

Usage

• To make your name of data file more clearly. • And we can use it for determine whether a

input in valid.

Library Functions<stdlib.h>

• atoi – Converts an ASCII string to an integer. Conversion

stops at the first noninteger character.• atof

– Converts an ASCII string to a double-precision number. Conversion stops at the first character that cannot be interpreted as a double.

• itoa– Converts an integer to an ASCII string.– Format: itoa(number,string,n)

DEALING WITH STRINGSSection B

Example

• Write a program that prompts the user to type in four character strings, places these in an array of strings, and then prints out: (e.g. I am Peter Pan)

1. The four strings in reverse order. (e.g. Pan Peter am I)

2. The four strings in the original order, but with each string backwards. (e.g. I ma reteP naP)

3. The four strings in reverse order with each string backwards. (e.g. naP reteP ma I)

way Ⅰ

• sscanf• Please see page 372 of the book1.Declare a character array2.Grammar: sscanf(character array name,

“format”, varieties to store the integer of the character)

Solution Ⅰ char x[40],a[4][10]; int i,j,b[4]; printf("\n\nPlease input four

words:"); gets(x); sscanf(x,"%s %s %s %s",

a[0],a[1],a[2],a[3]); for(i=3;i>-1;i--) printf("%s ",a[i]); printf(“\n");

Solution Ⅰ for(i=0;i<4;i++) b[i]=strlen(a[i])-1; for(i=0;i<4;i++) { for(j=b[i];j>=0;j--) printf("%c",a[i][j]);printf(" "); } printf("\n"); for(i=3;i>=0;i--) { for(j=b[i];j>=0;j--) printf("%c",a[i][j]);printf(" "); }

WAY Ⅱ

• Save as a string.1.Use Gets to receive the input and check

whether is it valid for your program.2.If that is valid, do the next step.

Solution Ⅱint i,j; char str[4][11]; printf("Please insert four strings :\n");for(i=0;i<4;i++) scanf("%s",&str[i]);printf("The four strings you have just input are:\

n");for(i=0;i<4;i++) printf(" %s",str[i]); printf("\n");

Solution Ⅱfor(i=3;i>=0;i--)printf(" %s",str[i]);printf("\n");

for(i=0;i<4;i++){ for(j=6;j>=0;j--) { printf("%c",str[i][j]); }} printf("\n");

for(i=3;i>=0;i--){ for(j=6;j>=0;j--) { printf("%c",str[i][j]); }}printf("\n");return 0;

Way Ⅲ

• Use the sentence• while((c = getchar()) && “conditions”)

Solution Ⅲ

• We omit it here. Because it isn’t good at dealing with strings

Summarize

• Use the method of coordinate can deal with the strings character by character.

INPUT VALIDATIONSection C

Exercise

• Write a C program that reads several positive numbers and uses the function round_to_nearest to round each of these numbers to the nearest integer. The program should print both the original number and the rounded number.

Answer

int main(){ float a; void round_to_nearest(float); printf("Please input a real number:"); scanf("%f",&a); round_to_nearest(a); return 0;}

Answer

void round_to_nearest(float a){ int z; float x; z=a;x=a-z; if(x>=0.5) z++; printf("\nthe original number is:%f",a); printf("\nthe rounded number is:%d",z);}

Question

• What will happen if I enter “AB.CD”???

How could that happen??????

Input Validation

• Because the input is invalid to the program.• A invalid value can cause so damaging errors

to your program.• So we should found the invalid input out.

Solution with Way Ⅰ

char apple[8];float number; printf(“please enter a number:”);gets(apple);sscanf(apple,“%f”,&number);

Solution with Way Ⅱint isfloat(char *c,int number){ int pdp=1,i,dec; if (*c != '-' && *c != '+' && (*c < '0' || *c >'9')) return 0; for (i=1;i<number;i++) if (*(c+i) == '.') {*(c+i)='0';dec = i;break;} for (i=1;i<number;i++) { pdp = pdp * isdigit(*(c+i)); if (pdp>1000) pdp=1; } *(c+dec) = '.'; if (pdp==0) dec=0; else dec=1; return dec;}

The String in functions

• We can’t pass a string into a function, because it is an array.

• We can only tell the function where the address of the first letter.

• We pass the address to the letter, and from that, we get all addresses.

• Then, we can change their value.

float getscore(void){ char c,i=0,n=0,number[9]; float score;while((c=getchar())!='\n') { if (c!=‘.’&&(c<‘0’||c>’9’)) {printf ("Warning: please enter a number!!!\n"); return -1.0;} if (c==‘.’) i=1; if (i==1&&c==‘.’) {printf("Warning:too much decimal point!\n");return -1.0;} if (n>=7) {printf("Warning:we only accept 6 digits!\n");return -1.0;} number[n++]=c; }score = atof(number); return score;}

Solution with Way ⅢCan be replaced by the function isdigit

What is it used for?

Summarize: sscanf

Advantage• Can save numbers and

strings at the same time.• Can easy turn every digits to

a value.

Disadvantage• Can not find invalid value

and give the user a warning.

Examplechar x[40],a[4][10]; int i,j,b[4]; printf("\n\nPlease input four words:"); gets(x); sscanf(x,"%s %s %s %s",

a[0],a[1],a[2],a[3]); for(i=3;i>-1;i--) printf("%s ",a[i]); printf("\n");

Summarize: Saving as strings

Advantages• Can check invalid inputs and

give the user a warning.• Can correct some invalid

inputs in some cases.

Disadvantages• if the length of the input is

not fixed, it will be very hard to control.

• It can be very hard to turn the strings to number.

Exampleint main(){ char K[100]; int i,k=1; while (k!=0) { k=0; printf("please type in your time(m:ss.kkk):"); gets(K); i=strlen(K); if (K[1]!=':'||K[4]!=‘.’) {k=1; } else {k[1]=0;k[4]=0;} if (i!=8) k=1; for (i=0;i<8;i++) if (K[i]<‘0’&&K[i]>‘9’) k=1; if (k==1) printf (“error! Please enter time as m:ss.kkk”); }

After we make sure the input is valid. We can use sscanf deal with the strings!

Summarize:Use while((c = getchar()) && “conditions”)

Advantages• Can check all kinds of wrong

input. And give responsible warnings!

Disadvantages• Can be too complex and

waste too much time!• Strongly recommend that

not to use this method while examination.

• Strongly recommend that use it when you design a program.

Example GetScore1: printf ("The score for \"easy to read\":"); scoreEasy = getscore(); if (scoreEasy>1.0 ||scoreEasy<0.0) {

printf("Note:the score should be in [0,1]!\n");goto GetScore1;

} printf ("the score is %3.1f\n",scoreEasy); i++;

goto

• The command ‘goto’ can be used everywhere in your program.

• Grammar: goto Linename;• You should name one line in your program in

your program as “getscore1:”

Note

• Most programmer don’t like ‘goto’ because it can cause confusions.

• We use some dead repetition instead.• Such as “while(1)”

float getscore(void){ char c,i=0,n=0,number[9]; float score;while((c=getchar())!='\n') { if (c!=‘.’&&(c<‘0’||c>’9’)) {printf ("Warning: please enter a number!!!\n"); return -1.0;} if (c==‘.’) i=1; if (i==1&&c==‘.’) {printf("Warning:too much decimal point!\n");return -1.0;} if (n>=7) {printf("Warning:we only accept 6 digits!\n");return -1.0;} number[n++]=c; } getchar(); score = atof(number); return score;}

How to set limit?

• Sometimes, we want to set a limit of length for our users. If the user input something too long, we have to ignore the last letters.

Methodwhile((c=getchar())&&(i++)<max) {……}if (n>=max) { while (1) { c=getchar(); if (c==‘\n’) break; } }

Another problem

• If one want to find the rounded number for several times, what should he do?

• Obviously, he can only run the program for lots of times. What would he think?

• How foolish the programmer are!

We change the program

int Num, ok=1;float num;do{ num = getscore(); if (num<1) { printf(“no negative please! \n”); continue; }Num = round_to_nearest(num);ok = Continue();}while(ok==0);

int Continue();do { char c; int ok=3; printf(“do you want to continue?(Y/N):”); c = getchar(); if (c!=‘\n’) getchar(); if (c==‘\n’ || c==‘y’ || c==‘Y’) ok = 0; if (c==‘n’||c==‘N’) ok =1; } while (ok==3);return ok;

continue

• Stop the reputation and re-start it from the beginning but all varieties will keep the current value.

By the way

• When we use the method III we always need the ASCII code for some characters. What should we do with that?

• In fact we can use Turbo C and ask the computer to show you the ASCII numbers.

Program

for (i=0;i<=255;i++;) printf(“%d---%c”, i,(char) i);

• Note the range of ASCII code is from -127 to 128

Input Validation

• This kind of processes are used for avoiding mis-input which caused by ‘enter’ hasn’t been got by your program.

• Moreover, you can design that if an user try too many times he can choose to exit. (Hint: use the exit() in <stdlib.h>)

New Year Gifts

• I have made several input validation sub-program in the library <DSINPUT.h>.

• I hope you can enjoy it!• There are six functions in my library.

<DSINPUT.H>

• in_p_int (int max) <max<=30000>– Ask the user enter a positive number smaller than

max value.• in_n_int (int min) <min>=-30000>

– Ask the user enter a negative number that larger than min value.

• in_int (int min, int max)– Ask the user enter a number that larger than min

value and smaller than min value.

• void goon()– Ask the user if he’d like to use the program again.

• in_float (int min, int max)– Ask the user enter a real number that larger than min

value and smaller than min value.• int isfloat(char *c,int number)

– *c is the head address of a string. Number is the length of the string

– Determine whether a string can be turned to real number.

• int isstring(char *str)– Determine whether is a string a sentence. If so return

1, otherwise return 0.

<DSINPUT.H>

FIND HELPSection D

Need help?

• Don’t go to the teacher or Zhangfan or me.• Try to think about it by yourself.• If you need more help please try to use the

help in turbo C. ,

Let me show some examples

• Study time functions.

Let me show some examples

• Study time functions.

For the function “delay”

The function “delay” ask the program have a pause before next command (ms)

A constant

Time functions

• In fact, the faction clock() doesn’t give the program a real time. What the function give to the program can be seemed as a “time number”.

• The constant CLK_TCK can turn the difference of “time number” to real time. The CLK_TCK equals to 18.200

Constant

• Study random functions

Let me show some examples

• Study random functions

Let me show some examples

Can be placed by time(NULL)If you do so, this sentence can be omitted

Let me show some examples

• Study random functions

rand

• The random function rand can only offer some fixed random number.

• If you run the same program for several times, the random numbers offered by rand() will always be the same numbers.

Example#include<stdio.h>#include<stdlib.h>int main(){ int i; for(i=1;i<=10;i++) printf ("number %d:%d\n",i,rand()); printf ("\n"); return 0;}

Output

Just the same

Let me show some examples

• Study random functions

random

• The random function rand can only offer some fixed random number.

• If you run the same program for several times, the random numbers offered by rand() will always be the same numbers.

Example#include<stdio.h>#include<stdlib.h>int main(){ int i; for(i=1;i<=10;i++) printf ("number %d:%d\n",i,random(10000)); printf ("\n"); return 0;}

Output

Just the same

Problem

• How can rand() and random() return a real random number?

• We can use randomize()

Let me show some examples

• Study random functions

Example Ⅰ#include<stdio.h>#include<stdlib.h>int main(){ int i; randomize(); for(i=1;i<=10;i++) printf ("number %d:%d\n",i,rand()); printf ("\n"); return 0;}

Output

Example Ⅱ#include<stdio.h>#include<stdlib.h>int main(){ int i; randomize(); for(i=1;i<=10;i++) printf ("number %d:%d\n",i,random(10000)); printf ("\n"); return 0;}

Output

More examples

• Game• TT

• Source code• Game• TT

• These programs use both time functions and random functions.

DEBUG YOUR PROGRAMSection E

method

• Find the value of your variety that might cause bugs.

• If all the value is right, check the following:– use ‘=’ properly or not– check the variety of left side and right side of ‘=’ is

in the right order.

WHITE PROGRAMSection F

Note

• check {} ()• use space properly• made the structure of your program more

clearly.• How to name your variety

The End

Thank you very muchConnect with me at

shengchenli@hotmail.com