18 Pages

day18

Course: EE 142, Spring 2009
School: Washington State
Rating:
 
 
 
 
 

Word Count: 1026

Document Preview

a Exercise Write program that accepts an input file containing integers representing daily high temperatures. Example input file: 42 45 37 49 38 50 46 48 48 30 45 42 45 40 48 Your program should print the difference between each adjacent pair of temperatures, such as the following: Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature...

Register Now

Unformatted Document Excerpt

Coursehero >> Washington >> Washington State >> EE 142

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
a Exercise Write program that accepts an input file containing integers representing daily high temperatures. Example input file: 42 45 37 49 38 50 46 48 48 30 45 42 45 40 48 Your program should print the difference between each adjacent pair of temperatures, such as the following: Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature Temperature changed changed changed changed changed changed changed changed changed changed changed changed changed changed by by by by by by by by by by by by by by 3 deg F -8 deg F 12 deg F -11 deg F 12 deg F -4 deg F 2 deg F 0 deg F -18 deg F 15 deg F -3 deg F 3 deg F -5 deg F 8 deg F 1 Solution #include <stdio.h> int main() { FILE *pFile = fopen("weather.txt", "r"); if (pFile == NULL) { printf("Could not open file. Exiting...\n"); exit(1); } int temp1, temp2; fscanf(pFile, "%d", &temp1); while (fscanf(pFile, "%d", &temp2) != EOF) { printf("Temperature changed by %d deg F\n", temp2 - temp1); temp1 = temp2; } } 2 Line-based processing 3 fgets man page SYNOPSIS #include <stdio.h> char *fgets(char *s, int n, FILE *stream); DESCRIPTION The fgets() function reads at most one less than the number of characters specified by n from the given stream and stores them in the string s. Reading stops when a newline character is found, at end-of-file or error. The newline, if any, is retained. If any characters are read and there is no error, a '\0' character is appended to end the string. RETURN VALUES Upon successful completion, fgets() returns a pointer to the string. If end-of-file occurs before any characters are read, it returns NULL and the buffer contents remain unchanged. 4 Who's next in line? Reading a file line-by-line, general syntax: FILE *pFile = fopen("<file name>", "r"); // do error-checking on file char buffer[1000]; while (fgets(buffer, 1000, pFile) != NULL) { <process the line in the buffer>; } NOTE: fgets stores the newline character ('\n') in the buffer. 5 Reading lines 23 3.14 John Smith 45.2 "Hello world" 19 19\n 23\t3.14 John Smith\t"Hello world"\n\t\t45.2 ^ fgets(buffer, 1000, pFile); 23\t3.14 John Smith\t"Hello world"\n\t\t45.2 ^ 19\n fgets(buffer, 1000, pFile); 23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n ^ 6 Exercise Write a program that reads a text file and "quotes" it by putting a > in front of each line. Input: Hey, How are you? computers. Sincerely, Your student This class is too much work. I hate Output: > > > > > > > Hey, How are you? computers. Sincerely, Your student This class is too much work. I hate 7 Solution #include <stdio.h> int main() { FILE *pFile = fopen("message.txt", "r"); // do error-checking on file char buffer[1000]; while (fgets(buffer, 1000, pFile) != NULL) { printf("> %s", buffer); } } Notice that since fgets copies the newline character to the buffer, we don't need a newline character at the end of the printf format string. 8 Example Example file contents: 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jennifer 8.0 8.0 8.0 8.0 7.5 Consider the task of computing the total hours worked for each person represented in the above file. Susan (ID#123) worked 31.4 hours (7.85 hours/day) Brad (ID#456) worked 36.8 hours (7.36 hours/day) Jennifer (ID#789) worked 39.5 hours (7.9 hours/day) 9 Line-based or token-based? Neither line-based nor token-based processing works. The better is solution a hybrid approach Break the input into lines. Break each line into tokens. 10 Processing lines FILE *pFile = fopen("<file name>"); // do error-checking on file while (fgets(buffer, 1000, pFile) != NULL) { <process this line>; } You can also use sscanf to interpret lines. It works like scanf and fscanf but takes it's input from a string. 11 Exercise Write a program that computes the total hours worked and average hours per day for a particular person represented in the following file: 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jennifer 8.0 8.0 8.0 8.0 7.5 7.0 Sample runs: (run #1) Enter a name: Brad Brad (ID#456) worked 36.8 hours (7.36 hours/day) (run #2) Enter a name: Harvey Harvey was not found 12 Searching for a line When going through the file, how do we know which line to process? If we are looking for a particular line, often we look for the token(s) of interest on each line. If we find the right value, we process the line. e.g. If the second token on the line is "Brad", process it. 13 Solution // This program searches an input file of employees' hours worked // for a particular employee and outputs that employee's hours data. #include <stdio.h> #include <string.h> #include <stdlib.h> void getSearchName(char *buffer); void getEmployeeData(char *searchName, char *line); void processLine(char *line); int main() { char name[1000]; getSearchName(name); char line[1000]; getEmployeeData(name, line); if (strlen(line) > 0) { processLine(line); } else { printf("%s was not found\n", name); } } 14 Solution void getEmployeeData(char *searchName, char *line) { line[0] = '\0'; // initialize to 0 length FILE *pFile = fopen("hours.txt", "r"); if (pFile == NULL) { printf("Could not open file. Exiting ..."); exit(1); } char buffer[1000]; while (fgets(buffer, 1000, pFile) != NULL) { int num; char name[1000]; sscanf(buffer, "%d %s", &num, name); // e.g. 456 Brad if (strcmp(name, searchName) == 0) { strcpy(line, buffer); } } } void getSearchName(char *buffer) { printf("Enter a name: "); scanf("%s", buffer); // e.g. "BRAD" } 15 Solution // totals the hours worked by one person and outputs their info void processLine(char *line) { char *pId = strtok(line, " "); // "456" char *pName = strtok(NULL, " "); // "Brad" double sum = 0.0; int count = 0; char *pToken = strtok(NULL, " "); while (pToken != NULL) { sum += atof(pToken); count++; pToken = strtok(NULL, " "); } double average = sum / count; printf("%s (ID#%s) worked %lf hours (%lf hours/day)", pName, pId, sum, average); } 16 Exercise Write a program that reads in a file containing HTML text, but with the tags missing their < and > brackets. Whenever you see any all-uppercase token in the file, surround it with < and > before you print it to the console. You must retain the original order of the tokens on each line. You will find the functions isupper and isalpha in ctype.h useful. 17 Exercise: Example input Input file: HTML HEAD TITLE My web page /TITLE /HEAD BODY P There are pics of my cat here, as well as my B cool /B blog, which contains I awesome /I stuff about my trip to Vegas. /BODY /HTML Output to console: <HTML> <HEAD> <TITLE> My web page </TITLE> </HEAD> <BODY> <P> There are pics of my cat here, as well as my <B> cool </B> blog, which contains <I> awesome </I> stuff about my trip to Vegas. </BODY> </HTML> 18
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Washington State - EE - 142
Object-oriented concepts1ExerciseWrite a program to produce the following output:p1 is (7, 2) p1's distance from origin = 7.280110 p2 is (4, 3) p2's distance from origin = 5.000000 p1 is (18, 8) p2 is (5, 10)The formula to compute the dis
Washington State - EE - 142
Object initialization: constructors1Initializing objectsIt is tedious to have to construct an object and assign values to all of its data fields manually.Point p; p.x = 3; p.y = 8;/ tediousWe want something more like:Point p(3, 8); / b
George Mason - SOCI - 101
Religion I. What is religion? a. Durkheim: A religion is a unified system or beliefs and practices relative to sacred things, that is to say, things set apart and forbidden beliefs and practices which united into one single moral community called a c
George Mason - SOCI - 101
The Family 1. U.S. census bureau defines a family as a group of two or more people (one of whom is a householder) related by birth, marriage, or adoption and residing together; all such people (including subfamily economic property, sexual access amo
George Mason - ECON - 103
CHAPTER1What Is Economics?After studying this chapter you will be able to Define economics and distinguish between microeconomics and macroeconomics Explain the two big questions of economics Explain the key ideas that define the economic way o
George Mason - ECON - 103
Economics 103 Microeconomic Principles7:20-10:00 PM, Tuesday EveningGeorge Mason University Spring 2009E.C. Holt, InstructorGeorge Mason Rich in Economic Excellence GMU has two Nobel Laureates, both in Economics (only VA University with two) P
George Mason - SOCI - 101
The Mass Media I. The mass media include radio, commercial television, cable television, newspapers, magazines, sound recordings, and the computer a. Defining characteristic is that each involves a single source that produces messages for a mass of i
George Mason - SOCI - 101
Conflict Theory: A theory of Power I. Karl Marx (1818-1883) a. Opening line of The Communist Manifesto (1848) reads: They history of all hitherto existing society is the history of class struggle. i. Problem began with the introduction of private pro
George Mason - SOCI - 101
I. II.III.Quantitative and Qualitative Methods Quantitative Methods: A Six Step Process 1. Problem Generation and Specification i. Seek confirmation of a theoretical assumption ii.Seek confirmation of a popular assumption 2. Reviewing the Literat
George Mason - SOCI - 101
Qualitative Sociological Research I. II. III. IV. V. VI. VII. Unobtrusive Measures-doesnt seem like anything was done Physical Trace Analysis-going through someones trash Archival Records-historians Content AnalysisCase Studies-experimental college C
George Mason - SOCI - 101
CultureI. II. Culture is everything we think, do, and have as members of a society Culture shapes our personalities A. Iroquois, Italian and American Males (Iroquois can neither cry or laugh in public, Italians can do both, and Americans can just la
George Mason - SOCI - 101
Socialization and Personality I. Socialization implied that the individual acquires a commitment to the norms, values, beliefs, and behavioral patterns of his or her society. We internalize the expectations A. The sociologist holds that the individua
George Mason - SOCI - 101
Theories of Crime and Deviance If youre not found guilty, than you are not a criminal I. A Functionalist Theory of Crime and DevianceKai Erikson a. The Function of Deviance in Small Groups (article) b. The Wayward Puritans (book) i. Why Puritans? ii.
George Mason - SOCI - 101
Interaction, Groups, and Organizations I. Textbook has 5 types of interactions A. Exchange B. Cooperation C. Competition D. Conflict E. Coercion Components of interaction and of society A. Statusa position in society B. Types of Statuses 1.Ascribed v
George Mason - SOCI - 101
Social Stratification and Inequality I. What is Stratification and Inequality? a. Social Inequality is a hierarchy of statuses and rules that enable some people to have more than others b. Social Stratification is a structured ranking process by whic
George Mason - SOCI - 101
Symbolic interactionism Someone in the upper class would be more confident in giving orders Lower class not so much Language plays a part in social classes -Lower classed kids were socialized more into society -Being compared to lower class, lower cl
George Mason - SOCI - 101
Race and Ethnicity 1. The Concept of Race a. A race is a group within the human species that is identified by a society as presumably having certain biologically inherited physical characteristics. Race is a socially constructed concept. We really sh
George Mason - SOCI - 101
I. II.III.IV.V. VI.Power-The probability to get someone to do what you want them to do whether they want to or not. (Max Weber) Some Important definitions A. Democracy: A political system that gives power to the people as a whole B. Monarchy:
George Mason - ECON - 103
CHAPTER8Possibilities, Preferences, and ChoicesAfter studying this chapter you will be able to Describe a households budget line and show how it changes when prices or income change Make a map of preferences by using indifference curves and exp
George Mason - ECON - 103
APPENDIX8Marginal Utility and Indifference CurvesAfter studying this chapter you will be able to Explain the connection between utility and indifference curves Explain why maximizing utility is the same as choosing the best affordable point Exp
George Mason - ECON - 103
CHAPTER9Organizing ProductionAfter studying this chapter you will be able to Explain what a firm is and describe the economic problems that all firms face Distinguish between technological efficiency and economic efficiency Define and explain t
George Mason - ECON - 103
CHAPTER1 0Output and CostsAfter studying this chapter you will be able to Distinguish between the short run and the long run Explain the relationship between a firms output and labor employed in the short run Explain the relationship between a
George Mason - ECON - 103
CHAPTER1 1Perfect CompetitionAfter studying this chapter you will be able to Define perfect competition Explain how firms make their supply decisions and why they sometimes shut down temporarily and lay off workers Explain how price and output
George Mason - ECON - 103
CHAPTER1 2MonopolyAfter studying this chapter you will be able to Explain how monopoly arises and distinguish between single-price monopoly and price-discriminating monopoly Explain how a single-price monopoly determines its output and price Co
George Mason - ECON - 103
CHAPTER13AMonopolistic CompetitionAfter studying this chapter you will be able to Define and identify monopolistic competition Explain how output and price are determined in a monopolistically competitive industry Explain why advertising costs
George Mason - ECON - 103
CHAPTER13 BOligopolyAfter studying this chapter you will be able to Define and identify oligopoly Explain two traditional oligopoly models Use game theory to explain how price and output are determined in oligopoly Use game theory to explain ot
George Mason - ECON - 103
CHAPTER1 4Regulation and Antitrust LawAfter studying this chapter you will be able to Explain the economic theory of government and how government activity arises from market failure and redistribution Define regulation and antitrust law and di
George Mason - ECON - 103
CHAPTER1 7Markets for Factors of ProductionAfter studying this chapter you will be able to Explain the link between a factor price and factor income Explain what determines demand, supply, the wage rate, and employment in a competitive labor ma
George Mason - ECON - 103
APPENDIX1 7Present Value and DiscountingAfter studying this appendix, you will be able to Explain how to calculate the present value of a future amount of money Explain how a firm uses a present value calculation to make an investment decision
George Mason - ECON - 103
CHAPTER1 8Economic InequalityAfter studying this chapter you will be able to Describe the inequality in income and wealth in the United States and the trends in inequality Explain the features of the labor market that contribute to economic ine
George Mason - ECON - 103
APPENDIX1Graphs in EconomicsAfter studying this chapter you will be able to Make and interpret a time-series graph, a cross-section graph, and a scatter diagram Distinguish between linear and nonlinear relationships and between relationships th