2014-11-20 4 views
-4

할당 :C - Senitel 제어 루프

A - 사용자가 "-1"을 입력 할 때까지 번호를 얻는 프로그램을 작성하십시오. 그런 다음 프로그램은 숫자를 파일에 써야합니다.

내가 이런 짓을했는지,하지만 난 B 하나를 수행 할 수 없습니다

B를 - 프로그램을 업데이트하고 아래 그림처럼 파일에 히스토그램을 인쇄 할 수 있습니다. 코드를 새 파일로 저장하십시오.

report.dat : ​​

5 *****
8 ********
11 ***********
A로부터 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

당신을 해달라고? 입력 숫자를 정수로 형변환하고 루프에서 필요한 별의 양을 생성해서는 안됩니다. –

+0

다음 줄 : scanf ("% d", &num);은 다음과 같이 작성해야합니다 : if (1! = scanf ("% scanf가 줄 바꿈/줄 바꾸기 (줄 바꿈과 같은)를 일으키게하려면 형식 문자열의 앞부분에 "?"이 붙는 것을 확인하십시오 (예 : "d", num)) {perror ("scanf" – user3629249

답변

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

코드의 나이 (영역). 파일 작업을 나중 단계로 분리하고 변수를 사용하여 히스토그램 값을 저장 한 다음 변수를 파일에 씁니다. 입력 한 번호를 하나의 배열에 저장하고 그 개수를 다른 배열에 저장하거나 struct에 결합하여 struct의 배열을 만들 수 있습니다. 새 struct에서 유형을 만들려면 typedef을 사용하십시오.

(불완전하지만 당신은 시작됩니다)이 같이

:

귀하의 첫 번째 단계는, 필요에 따라 그 성장이 배열을 생성하는 값을 채우고

두 번째 단계는 기록 -1 대기

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; 

저장된 모든 데이터를 파일로 저장합니다.

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