Introduction To C (and C) Programming

5m ago
23 Views
0 Downloads
7.39 MB
350 Pages
Transcription

Intro Classes Efficiency OOPIntroduction to C (and C) ProgrammingHans Petter Langtangen1,2Simula Research Laboratory1Dept. of Informatics, Univ. of Oslo2January 2006H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPOutline1234Intro to C programmingAbout C and C Introductory C exampleManipulate data filesMatrix-vector productThe C preprocessorExercisesAbout classes in C A simple classClass programmingClass ComplexA vector classStandard Template LibraryEfficiency; C vs. F77Object-Oriented Numerical ProgrammingOOP example: ODE solversClasses for PDEsH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPContentsGentle introduction to C File I/OArrays and loopsDetailed explanation of classes with built-in arithmeticsComputational efficiency aspectsObject-oriented programming and class hierarchiesUsing C objects in numerical applicationsH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPRequired backgroundProgramming experience with either Java or Fortran/MatlabInterest in numerical computing with C Interest in low-level details of the computerKnowledge of some C is advantageous (but not required)H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPAbout learning C C is a complicated computer languageIt takes time to master C – one year is the rule of thumbFour days can only give a taste of C You need to work intensively with C in your own projectsto master the languageC exposes you to lots of “low-level details” – these arehidden in languages like Java, Matlab and PythonHopefully, you will appreciate the speed and flexibility of C H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPTeaching philosophyIntensive course:Lectures 9-12Hands-on training 13-16Learn from dissecting examplesGet in touch with the dirty workGet some overview of advanced topicsFocus on principles and generic strategiesContinued learning on individual basisThis course just gets you started - use textbooks, referencemanuals and software examples from the Internet for futher workwith projectsH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPRecommended attitudeDive into executable examplesDon’t try to understand everythingTry to adapt examples to new problemsLook up technical details in manuals/textbooksLearn on demandStay coolH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesWhy do you need to learn “old” compiled languages?Because C, C , and Fortran (77/95) are the most efficientexisting tools for intensive numerical computingBecause tons of fast and well-tested codes are available inFortran, C/C Newer languages have emphasized simplicity and reliability –at the cost of computational efficiencyTo get speed, you need to dive into the details of compiledlanguages, and this course is a first, gentle stepH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesCC is a dominating language in Unix and WindowsenvironmentsThe C syntax has inspired lots of popular languages (Awk,C , Java, Perl, Python, Ruby)Numerous tools (numerical libraries, e.g., MPI) are written inC; interfacing them requires C knowledgeC is extremely portable; “all” machines can compile and run CprogramsC is very low level and close to the machineUnlimited possibilities; one can do anything in CProgrammers of high-level languages often get confused bystrange/unexpected errors in CH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC C extends C withnicer syntax:- declare variables wherever you want- in/out function arguments use references (instead of pointers)classes for implementing user-defined data typesa standard library (STL) for frequently used data types (list,stack, queue, vector, hash, string, complex, .)object-oriented programminggeneric programming, i.e., parameterization of variable typesvia templatesexceptions for error handlingC is a subset of C H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC versus other languagesFortran 77 is more primitive but more reliableMatlab is as simple/primitive as Fortran 77, but with manymore high-level commands ( easy to use)C is a superset of C and much richer/higher-level/reliableJava is simpler and more reliable than C Python is even more high-level, but potentially slowFortran 90/95 is simpler than Java/C and a goodalternative to CH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesSpeed of C versus speed of other languagesC is regarded as very fastFortran 77 may yield slightly faster codeC and Fortran 90/95 are in general slower, but C isvery close to C in speedJava is normally considerably slowerH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesSome guidelinesC programmers need to be concerned with low-level detailsthat C (and Java or Fortran) programmers can omitDon’t use C unless you have to - use C insteadThe best solution is often to combine languages: Python toadminister user interfaces, I/O and computations, withintensive numerics implemented in C or FortranH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesHigh vs low level programsGoal: make a window on the screen with the text “HelloWorld”Implementations in123C and the X11 libraryC and the Qt libraryPythonH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC/X11 implementation (1)#include stdio.h #include X11/Xlib.h #include X11/Xutil.h #define STRING#define BORDER#define FONT"Hello, world"1"fixed"XWMHintsxwmh {(InputHint StateHint),False,NormalState,0,0,0, 0,0,0,};H. P. Langtangen/*/*/*/*/*/*/*/*flags */input */initial state */icon pixmap */icon window */icon location */icon mask */Window group */Introduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC/X11 implementation (2)main(argc,argv)int argc;char **argv;{Display*dpy;Windowwin;GCgc;XFontStruct *fontstruct;unsigned long fth, pad;unsigned long fg, bg, bd;unsigned long bw;XGCValuesgcv;XEventevent;XSizeHints xsh;char*geomSpec;XSetWindowAttributes xswa;/*/*/*/*X server connection */Window ID */GC to draw with */Font descriptor *//*/*/*/*/*/*/*/*Font size parameters */Pixel values */Border width */Struct for creating GC */Event received */Size hints for window manager */Window geometry string */Temp. Set Window Attr. struct */if ((dpy XOpenDisplay(NULL)) NULL) {fprintf(stderr, "%s: can’t open %s\en", argv[0],XDisplayName(NULL));exit(1);}H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC/X11 implementation (3)if ((fontstruct XLoadQueryFont(dpy, FONT)) NULL) {fprintf(stderr, "%s: display %s doesn’t know font %s\en",argv[0], DisplayString(dpy), FONT);exit(1);}fth fontstruct- max bounds.ascent fontstruct- max bounds.descent;bd WhitePixel(dpy, DefaultScreen(dpy));bg BlackPixel(dpy, DefaultScreen(dpy));fg WhitePixel(dpy, DefaultScreen(dpy));pad BORDER;bw 1;xsh.flags (PPosition PSize);xsh.height fth pad * 2;xsh.width XTextWidth(fontstruct, STRING,strlen(STRING)) pad * 2;xsh.x ;xsh.y /2;win XCreateSimpleWindow(dpy, DefaultRootWindow(dpy),xsh.x, xsh.y, xsh.width, xsh.height,bw, bd, bg);H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC/X11 implementation (4)XSetStandardProperties(dpy, win, STRING, STRING, None,argv, argc, &xsh);XSetWMHints(dpy, win, &xwmh);xswa.colormap DefaultColormap(dpy, DefaultScreen(dpy));xswa.bit gravity CenterGravity;XChangeWindowAttributes(dpy, win,(CWColormap CWBitGravity), &xswa);gcv.font fontstruct- fid;gcv.foreground fg;gcv.background bg;gc XCreateGC(dpy, win,(GCFont GCForeground GCBackground), &gcv);XSelectInput(dpy, win, ExposureMask);XMapWindow(dpy, win);H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC/X11 implementation (5)}/** Loop forever, examining each event.*/while (1) {XNextEvent(dpy, &event);if (event.type Expose && event.xexpose.count 0) {XWindowAttributes xwa;intx, y;while (XCheckTypedEvent(dpy, Expose, &event));if (XGetWindowAttributes(dpy, win, &xwa) 0)break;x (xwa.width - XTextWidth(fontstruct, STRING,strlen(STRING))) / 2;y (xwa.height fontstruct- max bounds.ascent- fontstruct- max bounds.descent) / 2;XClearWindow(dpy, win);XDrawString(dpy, win, gc, x, y, STRING, strlen(STRING));}}exit(1);H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC /Qt implementation#include qapplication.h #include qlabel.h int main(int argc, char* argv[]){QApplication a(argc, argv);QLabel hello("Hello world!", 0);hello.resize(100, 30);a.setMainWidget(&hello);hello.show();return a.exec();}Point: C offers abstractions, i.e., complicated variables thathide lots of low-level details. Something similar is offered by Java.H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesPython implementation#!/usr/bin/env pythonfrom Tkinter import *root Tk()Label(root, text ’Hello, World!’,foreground "white", background "black").pack()root.mainloop()Similar solutions are offered by Perl, Ruby, Scheme, TclH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesTHE textbook on CKernighan and Ritchie: The C Programming LanguageH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesRecommended C textbooksStroustrup, Barton & Nackman, or Yang:More books puting.com/booklist/H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe first C encounterLearning by doing:Scientific Hello World: the first glimpse of C Data filter: reading from and writing to files, calling functionsMatrix-vector product: arrays, dynamic memory management,for-loops, subprogramsWe mainly teach C – the C version specialities are discussed atthe end of each example (in this way you learn quite some C withlittle extra effort)H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesScientific Hello World in C Usage:./hw1.app 2.3Output of program hw1.app:Hello, World! sin(2.3) 0.745705What to learn:123store the first command-line argument in a floating-pointvariablecall the sine functionwrite a combination of text and numbers to standard outputH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe code#include iostream // input/output functionality#include math.h // the sine function#include stdlib.h // the atof functionint main (int argc, char* argv[]){// convert the text argv[1] to double using atof:double r atof(argv[1]);// declare variables wherever needed:double s sin(r);std::cout "Hello, World! sin(" r ") " s ’\n’;return 0; /* success */}File: src/C /hw/hw1.cpp (C files have extension .cpp, .C or.cxx)H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesDissection (1)The compiler must see a declaration of a function before youcan call it (the compiler checks the argument and returntypes)The declaration of library functions appears in “header files”that must be included in the program:#include math.h // the sine functionWe use three functions (atof, sin, and std::cout ; theseare declared in three different header filesComments appear after // on a line or between /* and */(anywhere)On some systems, including stdlib.h is not required becauseiostream includes stdlib.hFinding the right header files (.h) is always a challengeH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesDissection (2)The main program is a function called mainThe command-line arguments are transferred to the mainfunction:int main (int argc, char* argv[])argc is the no of command-line arguments 1argv is a vector of strings containing the command-lineargumentsargv[1], argv[2], . are the command-line argsargv[0] is the name of the programH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesDissection (3)Floating-point variables in C and C :12float: single precisiondouble: double precisionatof: transform a text (argv[1]) to floatAutomatic type conversion: double floatThe sine function is declared in math.h(note: math.h is not automatically included)Formatted output is possible, but easier with printfThe return value from main is an int (0 if success)The operating system stores the return value, and otherprograms/utilities can check whether the execution was successful or notH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesAn interactive versionLet us ask the user for the real number instead of reading itfrom the command linestd::cout "Give a real number:";double r;std::cin r; // read from keyboard into rdouble s sin(r);// etc.H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesScientific Hello World in C#include stdlib.h /* atof function */#include math.h /* sine function */#include stdio.h /* printf function */int main (int argc, char* argv[]){double r, s;/* declare variables in the beginning */r atof(argv[1]); /* convert the text argv[1] to double */s sin(r);printf("Hello, World! sin(%g) %g\n", r, s);return 0;/* success execution of the program */}File: src/C/hw/hw1.c (C files have extension .c)H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesDifferences from the C versionC uses stdio.h for I/O and functions like printf for output;C can use the same, but the official tools are in iostream(and use constructions like std::cout r)Variables can be declared anywhere in C code; in C theymust be listed in the beginning of the functionH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesHow to compile and link C programsOne step (compiling and linking):unix g -Wall -O3 -o hw1.app hw1.cpp -lm-lm can be skipped when using g (but is otherwise normally required)Two steps:unix g -Wall -O3 -c hw1.cppunix g -o hw1.app hw1.o -lm# compile, result: hw1.o# linkNative C compiler on other systems:IBM AIX xlC -O2 -c hw1.cppIBM AIX xlC -o hw1.app hw1.o -lmother unix CC -O2 -c hw1.cppother unix CC -o hw1.app hw1.o -lmNote: -Wall is a g -specific optionH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesCollect compiler commands in a scriptEven for small test programs it is tedious to write thecompilation and linking commandsAutomate with a script!#!/bin/shg -Wall -O3 -c hw1.cppg -o hw1.app hw1.o -lmor parameterize the program name:#!/bin/shprogname 1g -Wall -O3 -c progname.cppg -o progname.app progname.o -lmH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesRunning the scriptSuppose the name of the script is compile.shMake the script executable:unix chmod a x compile.shExecute the script:unix ./compile.shor if it needs the program name as command-line argument:unix ./compile.sh hw1H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe make.sh scripts in the course softwareCompiler name and options depend on the systemTip: make a script make.sh to set up suitable default compilerand options, and go through the compilation and linkingWith this course we have some make.sh scripts usingenvironment variables in your start-up file (.bashrc, .cshrc):# C compiler and associated options:CPP COMPILERCPP COMPILER OPTIONSIf not defined, these are set according to the computer systemyou are on (detected by uname -s)H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe make.sh script (1)#!/bin/sh# determine compiler options (check first if the environment# variable CPP COMPILER is set):if [ ! -n " CPP COMPILER" ]; then# base CPP COMPILER on the current machine type:case ‘uname -s‘ inLinux)CPP COMPILER g CPP COMPILER OPTIONS "-Wall -O3";;AIX)CPP COMPILER xlCCPP COMPILER OPTIONS "-O";;SunOS)CPP COMPILER CCCPP COMPILER OPTIONS "-O3";;*)# GNU’s gcc is available on most systems.C COMPILER gccC COMPILER OPTIONS "-Wall -O3";;esacfiH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe make.sh script# fetch all C files:files ‘/bin/ls *.cpp‘for file in files; dostem ‘echo file sed ’s/\.cpp //’‘echo CPP COMPILER CPP COMPILER OPTIONS -I. -o stem.app file -lm CPP COMPILER CPP COMPILER OPTIONS -I. -o stem.app file -lmls -s stem.appdoneH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesHow to compile and link C programsTo use GNU’s compiler: just replace g by gccOn other systems:IBM AIX xlc -O2 -c hw1.cIBM AIX xlc -o hw1.app hw1.o -lmother unix cc -O2 -c hw1.cother unix cc -o hw1.app hw1.o -lmH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesHow to compile and link in generalWe compile a bunch of Fortran, C and C files and linkthese with some librariesCompile each set of files with the right compiler:unix g77 -O3 -I/some/include/dir -c *.funix gcc -O3 -I/some/other/include/dir -I. -c *.cunix g -O3 -I. -c *.cppEach command produces a set of corresponding object fileswith extension .oThen link:unix g -o executable file -L/some/libdir -L/some/other/libdir \*.o -lmylib -lyourlib -lstdlibHere, we link all *.o files with three libraries: libmylib.a,libyourlib.so, libstdlib.so, found in /some/libdir or/some/other/libdirLibrary type: lib*.a: static; lib*.so: dynamicH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesExecutables vs. librariesA set of object files can be linked with a set of libraries toform an executable program, provided the object files containsone main programIf the main program is missing, one can link the object files toa static or sheared library mylib2:unix g -shared -o libmylib2.so *.ounix g -static -o libmylib2.a *.oIf you write a main program in main.cpp, you can create theexecutable program byunix g -O -c main.cpp # create main.ounix g -o executable file main.o -L. -lmylib2H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesMakefilesCompiling and linking are traditionally handled by makefilesThe make program executes the code in makefilesMakefiles have an awkward syntax and the make language isprimitive for text processing and scriptingThe (old) important feature of make is to check time stampsin files and only recompile the required filesI have stopped using makefiles – I prefer plain scriptsH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThings can easily go wrong in CLet’s try a version of the program where we fail to includestdlib.h (i.e. the compiler does not see the declaration ofatof)unix gcc -o tmp -O3 hw-error.cunix ./tmp 2.3Hello, World! sin(1.07374e 09) -0.617326File: src/C/hw/hw-error.cThe number 2.3 was not read correctly.argv[1] is the string "2.3"r is not 2.3 (!)The program compiled and linked successfully!H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesRemedyUse the C compiler, e.g.unix g -o tmp -O3 hw-error.chw-error.c: In function ‘int main(int, char **)’:hw-error.c:9: implicit declaration of function ‘int atof(.)’or use gcc -Wall with gcc:unix gcc -Wall -o tmp -O3 hw-error.chw-error.c: In function ‘main’:hw-error.c:9: warning: implicit declaration of function ‘atof’The warning tells us that the compiler cannot see the declarationof atof, i.e., a header file with atof is missingH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesExample: Data transformationSuppose we have a file with xy-data:0.1 1.10.2 1.80.3 2.20.41.8and that we want to transform the y data using somemathematical function f(y)Goal: write a C program that reads the file, transforms they data and write new xy-data to a new fileH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesProgram structure1Read name of input and output files as command-linearguments2Print error/usage message if less than two command-linearguments are given3Open the filesWhile more data in the file:41235read x and y from the input fileset y myfunc(y)write x and y to the output fileClose the filesFile: src/C /datatrans/datatrans1.cppH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe C code (1)#include#include#include#include iostream fstream iomanip math.h double myfunc(double y){if (y 0.0) {return pow(y,5.0)*exp(-y);} else {return 0.0;}}int main (int argc, char* argv[]){char* infilename; char* outfilename;/* abort if there are too few command-line arguments */if (argc 2) {std::cout "Usage: " argv[0] " infile outfile" ’\n’;exit(1);} else {infilename argv[1]; outfilename argv[2];}H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe C code (2)}std::ifstream ifile( infilename);std::ofstream ofile(outfilename);std::cout argv[0] ": converting " infilename " to " outfilename ’\n’;double x, y;int ok true; // boolean variable for not end of filewhile (ok) {if (!(ifile x y)) ok false;if (ok) {y myfunc(y);ofile.unsetf(std::ios::floatfield);ofile x " ";ofile.setf(std::ios::scientific, std::ios::floatfield);ofile.precision(5);ofile y std::endl;}}ifile.close(); ofile.close();return 0;We can avoid the prefix std:: by writingusing namespace std; /* e.g.: cout now means std::cout */H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC file openingFile handling in C is implemented through classesOpen a file for reading (ifstream):#include fstream const char* filename1 "myfile";std::ifstream ifile(filename1);Open a file for writing (ofstream):std::string filename2 filename1 ".out"std::ofstream ofile(filename2); // new output fileor open for appending data:std::ofstream ofile(filename2, ios base::app);H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesC file reading and writingRead something from the file:double a; int b; char c[200];ifile a b c; // skips white space in betweenCan test on success of reading:if (!(ifile a b c)) ok 0;Print to file:ofile x " " y ’\n’;Of course, C’s I/O and file handling can be used#include cstdio // official C name for stdio.hcall ios::sync with stdio() if stdio/iostream are mixedH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesFormatted output with iostream toolsTo set the type of floating-point format, width, precision, etc,use member functions in the output object:ofile.setf(std::ios::scientific, std::ios::floatfield);ofile.precision(5);I find such functions tedious to use and prefer printf syntaxinsteadH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesFormatted output with printf toolsThe iostream library offers comprehensive formatting controlprintf-like functions from C makes the writing faster(and more convenient?)Writing to standard output:printf("f(%g) %12.5e for i %3d\n",x,f(x),i);There is a family of printf-like functions:123printf for writing to standard outputfprintf for writing to filesprintf for writing to a stringWriting to a file: use fprintf and C-type files, or use C files with the oform tool on the next slideH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesA convenient formatting tool for C Use the C function sprintf to write to a string withprintf-like syntax:char buffer[200];sprintf(buffer, "f(%g) %12.5e for i %3d",x,f(x),i);std::cout buffer;This construction can be encapsulated in a function:std::cout oform("f(%g) %12.5e for i %3d",x,f(x),i);char* oform (const char* fmt, .) /* variable no of args! */{va list ap; va start(ap, fmt);static char buffer[999]; // allocated only oncevsprintf (buffer, fmt, ap);va end(ap);return buffer;}static variables in a function preserve their contents from callto callH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe printf syntaxThe printf syntax is used for formatting output in manyC-inspired languages (Perl, Python, awk, partly C )Example: writei 4, r 0.7854, s 7.07108E-01, method ACCi.e.i [integer in a field of width 2 chars]r [float/double written as compactly as possible]s [float/double written with 5 decimals, in scientific notation,in a field of width 12 chars]method [text]This is accomplished byprintf("i %2d, r %g, s %12.5e, method %s\n", i, r, s, method);H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesMore about I/O in C General output object: ostreamGeneral input object: istreamifstream (file) is a special case of istreamofstream (file) is a special case of ostreamCan write functionsvoid print (ostream& os) { . }void scan (istream& is) { . }These work for both cout/cin and ofstream/ifstreamThat is, one print function can print to several different mediaH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesWhat is actually the argv array?argv is an array of strings# C/C declaration:char** argv;# orchar* argv[];argv is a double pointer; what this means in plain English isthat123there is an array somewhere in memoryargv points to the first entry of this arrayentries in this array are pointers to other arrays of characters(char*), i.e., stringsSince the first entry of the argv array is a char*, argv is apointer to to a pointer to char, i.e., a double pointer (char**)H. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesThe argv double pointerchar**some stringchar*char*abcchar*some running text .NULLH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesType conversionThe atof function returns a float, which is then stored in adoubler atof(argv[1]);C/C transforms floats to doubles implicitlyThe conversion can be written explicitly:r (double) atof(argv[1]);r double(atof(argv[1]));/* C style */// C styleExplicit variable conversion is a good habit; it is safer thanrelying on implicit conversionsH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesData transformation example in CSuppose we have a file with xy-data:0.1 1.10.2 1.80.3 2.20.41.8and that we want to transform the y data using somemathematical function f(y)Goal: write a C program that reads the file, transforms the ydata and write the new xy-data to a new fileH. P. LangtangenIntroduction to C (and C) Programming

Intro Classes Efficiency OOPC/C Hello World I/O A*x Macros Exercises ClassesProgram structure1Read name of input and output files as command-linearguments2Prin