2014-11-20 54 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