2014-11-20 56 views
-4

作业:C - Senitel控制回路

A - 编写一个程序,从用户获取数字,直到用户输入“-1”。然后程序应该将数字写入文件。

我已经这样做了,但我不能做B中的一个:

乙 - 更新您的程序和打印直方图到该文件如下所示。将您的代码保存在一个新文件中。

report.dat:

5 *****
8 ********
11 ***********
3 ***

代码在:

#include <stdio.h> 
    int main() { 
    int num; 
    const int senitel = -1; 
    FILE*fileId; 
    printf("Please enter integer number (-1 to finish)"); 
    scanf("%d", &num); 
    fileId = fopen("report.dat", "w"); 
    while (num != senitel) { 
     fprintf(fileId, "%d \n", num); 
     scanf("%d", &num);  
    } 

    fclose(fileId); 
    return 0; 
} 
+0

我认为你唯一缺少的星星在每行的末尾,不好吗?应该不会那么难以将输入数字转换为整数并在循环中创建您需要的恒星数量 – 2014-11-20 21:46:32

+0

这些行:scanf(“%d”,&num);应写为:if(1!= scanf(“注意格式化字符串中的前导'',以使scanf跳过/消耗空白(如换行符) – user3629249 2014-11-20 23:29:35

回答

1

不需要将用户输入直接写入文件,而需要暂时将其存储在数据结构中。当用户输入标记值时,输出数据结构的内容。

在伪

ask user for input 
while not sentinel 
    add to array[user value]++ 
    get next input 

for each element in array 
    if value > 0 
     fprintf value + " " 

     for (int i = 0; i < value; i++) 
      fprintf "*" 

     fprintf 
0

你正在尝试做一个ST两个步骤年龄(地区)代码。将文件操作分成稍后阶段,并使用变量存储直方图值,并将变量写入文件。您可以将输入的号码存储在一个阵列中,并将该号码的计数存储在另一个阵列中 - 或将两者合并为一个struct并创建一个struct的阵列。使用typedef从您的新struct制作一个类型。

像这样(不完全的,但将让你开始):

typedef struct tag_HistogramRow { 
    long EnteredNumber; 
    long Count; 
} t_HistogramRow; 

t_HistogramRow *typMyHistogram=NULL; // Pointer to type of t_HistogramRow, init to NULL and use realloc to grow this into an array 
long lHistArrayCount=0; 

你的第一步是创建这个数组,它生长在必要时,在填写值并等待-1

第二步写道:将所有存储的数据存档。

0
the lines: 

while (num != senitel) { 
    fprintf(fileId, "%d \n", num); 
    scanf("%d", &num);  
} 

would become: 

while (num != senitel) 
{ 
    // echo num to file 
    fprintf(fileId, "%d ", num); 

    // echo appropriate number of '*' to file 
    for(int i= 0; i<num; i++) 
    { 
     fprintf(fileId, "*"); 
    } // end if 

    // echo a newline to file 
    fprintf(fileId, "\n"); 

    // be sure it all got written to file before continuing 
    fflush(fileId); 

    // note: leading ' ' in format string enables white space skipping 
    if(1 != scanf(" %d", &num)) 
    { // then, scanf() failed 
     perror("scanf"); // also prints out the result of strerror(errno) 
     exit(1); 
    } // end if  
} // end while