#11 (03/04/2024)

String manipulation

#include <stdio.h>
int main()
{
float a=2.0;
printf("%f\n",a);
return 0;
}
#include <stdio.h>
int main()
{
char a='A';
printf("%c\n",a);
return 0;
}
#include <stdio.h>
int main()
{
float a[]={2.0, 3.0, 4.0, 5.0};
printf("%f\n",a[0]);
return 0;
}
#include <stdio.h>
int main()
{
char a[]="MAE2360";
printf("%c\n",a[0]);
return 0;
}
Note: In the example above, when a string MAE2360 is assigned to an array, a, the system automatically adds a character with the ASCII code 0 to indicate that it is the end of the string. Therefore, the size of a is 7, not 6, a[7].
Use the %s format to represent the entire string instead of the %c format that represents only one character.
#include <stdio.h>
int main()
{
char *a;
a="MAE2360";
printf("%c\n",a[0]);
return 0;
}
#include <stdio.h>
int main()
{
char *a;
a="MAE2360";
printf("%s\n",a);
return 0;
}

"ABC" (double quotation) is for a string of characters and is an array (pointer).
'A' (single quotation) is for a single character !!

Consider this example:
#include <stdio.h>
int main()
{
  char s[4] = "ABC";

  printf("%s\n", s);
  return 0;
}
To read a string from the standard input (i.e. keyboard),
#include <stdio.h>
int main()
{
char str[100];
printf("Enter string = ");
scanf("%s", str);
printf("%s\n",str);
return 0;
}
Note that there is no "&" before str in the scanf function as "str" is already a pointer. The C compiler automatically adds "\0" after the end of the last character in the string.

String copy/compare/length

To copy a string to another string or to compare a string against another string, it is best to use functions, strcpy and strcmp, found in string.h (you can avoid all the hassles associated with pointer manipulation). Reference to C functions
#include <stdio.h>
#include <string.h>
int main()
{
    char c1[] = "ABCDE", c2[6];

    strcpy(c2,c1);
    printf("%s\n",c2);
    return 0;
}
The function, strcpy(c2,c1), copies the contents pointed by c1 to the address pointed by c2. Note that this is not the same as copying a pointer c1 to another pointer c2.
To compare two strings, use strcmp found in string.h.
#include <stdio.h>
#include <string.h>

int main()
{
    char s[100];

    printf("Enter \"MAE2360\" = ");
    scanf("%s", s);

    if (strcmp(s,"MAE2360") == 0) printf("MAE2360 was entered correctly.\n");
    
    else printf("Wrong. %s was entered.\n",s);
    return 0;
}
The strcmp function takes two strings as the arguments and returns 0 if the two strings match. Note that you can output " (double quotation mark) by "escaping" it using the backslash character.
To find the length of the string, you may want to use the strlen function.
#include <stdio.h>
#include <string.h>
int main()
{
char c[50];
printf("Enter string = ");
scanf("%s", c);
printf("You entered %s\n", c);
printf("Its length is %d\n", strlen(c));
return 0;
}

File handling (from DOS/Shell prompt)

I/O Redirection (Standard input/output redirection)

Notion Meaning
$ a.out > filename output to file
$ a.out >> filename append output to file
$ a.out < filename get input from file

$ gcc junk.c
$ a.out > result.dat
$ more result.dat


$ gcc junk2.c
$ a.out < data.dat > result.dat
$ more result.dat


c:\dir > filelist.dat

File handling (from within a program)


#include <stdio.h>

int main()
{
	FILE *fp;
 	fp = fopen("filename","w");
   /*
      write something on fp 
   */
	fclose(fp);
        return 0;
}

The function, fopen, takes a (append), w (write) or r (read) as possible arguments.

#include <stdio.h>
int main()
{
	FILE *fp;
	fp=fopen("junk.dat","w");
	fprintf(fp,"Hello!\n");
	fclose(fp);
        return 0;
}


#include <stdio.h>
int main()
{
	FILE *fp; float a,b,c;
	fp=fopen("junk.dat","r");
	fscanf(fp,"%f %f %f", &a, &b, &c);

	printf("%f %f %f", a,b,c);

	fclose(fp);
        return 0;
}


#include <stdio.h>
int main()
{
	FILE *fp1, *fp2; 
        float a,b,c;
	fp1=fopen("junk1.dat","w");
        fp2=fopen("junk2.dat","w");
	fprintf(fp1,"This is the first file.\n");
	fprintf(fp2,"This is the second file.\n");

	fclose(fp1); fclose(fp2);
        return 0;
}

Command line parameters

$ gcc -lm junk.c -o junk
$ junk 
(interactive session)
$ gcc -lm junk.c -o junk
$ junk 3421 8756
(executes program to manipulate 3421 and 8756 and prints results)
int main(int argc, char *argv[])
The first argument, argc (=argument count), is of integer type and is assigned the number of command line arguments including the command name itself. The second argument, argv (=argument vector), is a pointer to an array of strings and is assigned pointers to each command line argument. Note that argv[] is an array so that it can take multiple command line arguments. 1
#include <stdio.h>

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

  printf("Number of parameters = %d\n", argc);

  for(i=0; i<argc; i++)
    printf("%d: %s\n", i, argv[i]);
  
  return 0;
}
atoi (ASCII to INTEGER) or atof (ASCII to FLOAT) found in the stdlib.h library.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
printf("%d\n", atoi(argv[1]));
return 0;
}
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
int i;
int b[100]; /* reserve ample space*/

for (i=1; i< argc; i++)
b[i]=atoi(argv[i]);

for (i=1; i< argc ; i++)
 printf("%d\n", b[i]);

return 0;
}

Structures

#include <stdio.h>

int main()
{
	int a[4][2]={{89, 76},{65, 91}, {56, 78}, {49, 56}};

        return 0;
}
#include <stdio.h>

struct student{
        char *ID;
        int Midterm;
        int Final;
        char Grade;
		};
int main()
{
  struct student smith={"1000123456", 89, 98, 'A'},
                 doe={"1000123457", 45, 53, 'F'},
                 jones={"1000123458", 67, 80, 'C'};

  printf("%s\n", smith.ID);
  printf("%c\n", jones.Grade);
  printf("%d\n", doe.Midterm);

  doe.Midterm=79;
  doe.Grade='D';

  printf("%c\n", doe.Grade);

  return 0;
}
As seen in the example above, a member in a structure can be accessed by using the dot (.).
#include <stdio.h>

struct student{
        char *Name;
        int Midterm;
        int Final;
        char Grade;
		};
int main()
{
  struct student fall[15];
  int i;
  FILE *data;
  data=fopen("junk.dat", "r");

  for (i=0;i<15;i++)
   fscanf(data, "%s %d %d %c", 
        fall[i].Name, &fall[i].Midterm, &fall[i].Final, &fall[i].Grade);
  fclose(data);

  printf("%d\n", fall[0].Midterm);
  printf("%s\n", fall[0].Name);

  return 0;
}
Doe 45 47 F
Jones 89 65 B
Smith 76 79 B
........
#include <stdio.h>

struct student{
        char *Name;
        int Midterm;
        int Final;
        char Grade;
		};
int main()
{
  struct student fall[3]= { {"Jones", 45, 65, 'D'}, {"Doe", 98, 79, 'B'}, {"Smith", 67, 76, 'C'}};
/*
..................
*/
  printf("%s %d %d %c\n", fall[0].Name, fall[0].Midterm, fall[0].Final, fall[0].Grade);
  return 0;
}
It is also possible to use a pointer to a structure as
#include <stdio.h>

struct student{
        char *Name;
        int Midterm;
        int Final;
        char Grade;
		};
int main()
{
  struct student Smith={"David Smith", 12, 45, 'F'}, *ptr;
  ptr = &Smith;
/*
..................
*/

  printf("%s %d %d %c\n", ptr->Name, ptr->Midterm, ptr->Final, ptr->Grade);
  return 0;
}
Note that a member in a structure can be referred by using ->.
Finally, by using typedef, you can define a structure and declare a variable as that structure type just like integer or float.
#include <stdio.h>
typedef struct {
        char *Name;
        int Midterm;
        int Final;
        char Grade;
      } student;

int main()
{
  student Jones={"Jones", 12, 45, 'F'}, *ptr;
  ptr = &Jones;
/*
..................
*/

 printf("%s\n", ptr->Name);
  return 0;
}
The concept of structure is extended to the concept of class which plays an essential role in C++ (and Java).
The following code defines the complex type (a + b i) and computes addition of two complex numbers:
#include <stdio.h>

typedef struct
 {float Real; float Im;} Complex;

Complex ComplexAdd(Complex z1, Complex z2)
{
	Complex z;
	z.Real = z1.Real + z2.Real;
	z.Im = z1.Im + z2.Im;
	return z;
}

int main()
{
	Complex z1, z2, z;

	printf("Enter real and imaginary parts of z1 separated by space = ");
	scanf("%f %f", &z1.Real, &z1.Im);

        printf("Enter real and imaginary parts of z2 separated by space = ");
	scanf("%f %f", &z2.Real, &z2.Im);

	z = ComplexAdd(z1, z2);

	printf("%f + %f I \n", z.Real, z.Im);
	return 0;
}

Closure on C syntax

  1. What happened to the arguments of main() ?
    See Lecture note #10.
  2. What does "return 0;" really mean ?
    The OS requires a return value when you run a program. Depending on the return value, the OS knows whether the program you run exit successfully or not.


Footnotes:

1 Actually, argv[] is a pointer to another pointer (an array of another array) as each element of argv[] is a string of characters.


File translated from TEX by TTH, version 4.03.
On 03 Mar 2024, 18:22.