我正在编写一个程序,从用户那里获取一些东西,然后将结果写入一个文件。程序将得到文件名、要生成的数字、要生成的最低和最高数字,然后将其全部写入由用户命名的文件。
程序正在做两件不正确的事情:
它正在生成用户指定范围之外的数字
它在添加一个?在文件名的末尾,我尝试使用strlen删除字符串的最后一个字符,但我得到并出错:内置函数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;
}

最佳答案

关于文件名:删除'\n'之后'\x0a'结尾的换行符s(或fgets()):

if( s[strlen(s)-1] == '\n' )
     s[strlen(s)-1] = '\0';

完整性:在windows上,您必须删除回车+换行符'\r'+'\n'(或'\x0d'+'\x0a'
关于错误的数字:它应该是x = (rand() % a) + l;(模数范围+最低值,而不是相反)

关于c - C程序,用于从用户获取文件名和数字范围,从指定范围生成数字并打印到文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30626477/

10-11 23:05
查看更多