mercredi 3 juin 2015

C Program to get file name and range of numbers from user generate numbers from a specified range and print to file

I am writing a program to get a few things from the user and then write the results to a file. The program will get the file name, number of numbers to generate, the lowest and highest numbers to be generate, then write it all to a file that is named by the user.

The program is doing two things that are not correct:

  1. it is generating numbers outside the user specified range

  2. it is adding a ? to the end of the file name, I tried using strlen to remove the last character of the string but I get and error: incompatible implicit declaration of built-in function 'strlen'.

#include <stdio.h>
#include <stdlib.h>

int main()
{
 char s[100];
 FILE *fout;
 int i, x, len;
 int h, l, q, a;

 printf("Please enter the file name: ");
 fgets(s, sizeof(s), stdin);
 printf("How many numbers should we generate: ");
 scanf("%d", &q);
 printf("lowest number to generate: ");
 scanf("%d", &l);
 printf("Highest number to generate: ");
 scanf("%d", &h);

 fout = fopen(s, "wb");

 a = h - l;

 if ( fout == NULL)
 {
  printf("That file is not available\n");
  exit(1);
 }

 fprintf(fout, "%d\n", q);

 for (i=0; i < q; ++i) 
 {
  x = (rand() % l) + a;
  fprintf(fout, "%d ", x);
 }

fclose(fout);
return 0;
}




Aucun commentaire:

Enregistrer un commentaire