L-31 MCS 275 Wed 28 Mar 2001

Below are the programs we discussed in class.

Another good use of the scan set in combination with sscanf() and sprintf().

/* L-31 MCS 275 Wed 28 Mar 2001 breaking strings with sscanf() */

/* The program below reads a line and breaks the string up into two
   strings with the cut at the first encountered a in the line.
   Then with sprintf(), a new string is made, concatenating the
   two new strings, with the second string in first position.
   For example, if the user types in "this is a test", then the
   program displays "a test this is". */

#include <stdio.h>

int main()
{
   char line[80],before[80],after[80],newline[80];

   printf("Give a line (<80 chars) : ");
   scanf(" %79[^\n]", line);               /* skips leading spaces */
   printf("-> Your line is : %s\n", line);

   after[0] = '\0';             /* in case no a occurs in the line */

   sscanf(line,"%[^a]%[^\n]", before, after);

   printf("first part  : %s\n", before); 
   printf("second part : %s\n", after); 

   sprintf(newline,"%s %s", after, before);
   printf("The new line : %s\n", newline);

   return 0;
}
Here is an application on the use of stdout and stderr. When we redirect the output of the program below to a file (that is: execute the program like a.out > output & on UNIX machine), we still want be able to interact with the user. The ampersand (&) is needed to keep the program running in the background. The dialogue with the user will not be part of the output file.
#include <stdio.h>

/* L-31 MCS 275 Wed 28 Mar 2001 illustration of stderr */

/* runs the program (compiled version primes) below as 
     primes > output &
   The user can set the number of primes to be printed next.  */

int is_prime( long int n );
/* returns 1 if the number is prime, 0 if it is not */

int main()
{
   int i;
   long int max = 1;
   long int n,start,cnt;
   long int more = 10;

   for (i = 0; i < 30; i++)
      max = 2*max;

   printf("Printing primes up to 2^30 = %d.\n", max);

   cnt = 0;
   start = 0;
   for (n = 1; (n < max) && (more > 0); n++)
      if (is_prime(n) == 1)
      {
         cnt++;
         fprintf(stdout,"prime %d is %d\n", cnt, n);
         if (start + more <= cnt)
         {
            fprintf(stderr,"Printed %d primes.  How many more? ", cnt);
            fscanf(stdin,"%d", &more);
            start = cnt;
         }
      }

   return 0;
}

int is_prime( long int n )
{
   long int i;

   for (i = 2; i < n; i++)
      if (n % i == 0)
         return 0;

   return 1;
}