Почему оператор printf выполняется бесконечно? - PullRequest
0 голосов
/ 01 мая 2018

Заголовочный файл, используемый в программе.

#ifndef choice_h
#define choice_h
#include <stdio.h>
#include <stdlib.h>


int choice_list(){
int option;

puts("DATA CONFIRMATION AND UPDATE PROGRAM\n\n");
puts("1. Display data set now.\n");
puts("2. Delete an entry from the data set.\n");
puts("3. Add an entry to the end of the data set.\n");
puts("4. Change an existing entry.\n");
puts("5. Quit this program.\n");
puts("Enter choice [ 1-5, 0 = change data set]:");
scanf("%d", &option);

//this while loop tests against numbers [0-5] the choice called "option" that 
//was input by the user. Option needs to be in the range of [0-5] 
//in order for the user to select from the program menu.
while (!(0 == option || 1 == option || 2 == option || 3 == option || 4 == option || 5 == option))
{
    printf("\nInvalid Entry, please enter [0-5]: ");
    scanf("%d", &option);
}

 //this if statement is an echo print to check the selected option
if (0 == option || 1 == option || 2 == option || 3 == option || 4 == option || 5 == option) {

    printf("you selected option: [%d]\n", option);
}

return option; //returns to calling function
}


 #endif /* choice_h */

=============================================== ====

основная программа: это не вся моя программа. Я только отправил до того места, где произошла ошибка.

 #include <stdio.h>
 #include <stdlib.h>
 #include "../include/myheader.h"
 #include "../include/lab7_arrays.h"
 #include "../include/choice_list.h"

 int option_0(int ptr[]);
 int option_1(int ptr[]);
 int option_2(int ptr[]);
 int option_3(int ptr[]);
 int option_4(int ptr[]);

 main(){

 int data_1[MAX_VALUES] = {4, 7, 6, 32, 5};
 int data_2[MAX_VALUES] = {98, 47, 26, 99, 187};

    int option, choice;

    my_identity();
    print_arrays();
    puts("\nWhich set do you want to update [1 or 2]: ");
    scanf("%d", &choice);

//  this while loop checks and prompts the user to input an accepted value (1 or 2)
    while (!(1 == choice || 2 == choice))
    {
printf("\nInvalid Entry, please enter 1 or 2: ");
    scanf("%d", &choice);
    }

if (1 == choice || 2 == choice)
    printf("\nDisplaying options for data set %d...\n\n", choice);

 //function defined in header file   
 option = choice_list();
    printf("option = %d choice = %d", option, choice);

/ ***** БЕСКОНЕЧНЫЙ ЦИКЛ НАЧИНАЕТСЯ ЗДЕСЬ: просто продолжает печатать опцию и выбор, пока я не заставлю выйти из программы ******* /

    while (choice == 1||choice == 2)
    {
            if(choice == 1)
            { int *ptr = data_1;
              printf("choice: %d option: %d", choice, option);
                    switch(option)
                    {   case 0: option_0(ptr);
                                    break;
                            case 1: option_1(ptr);
                                    break;
                            case 2: option_2(ptr);
                                    break;
                            case 3: option_3(ptr);
                                    break;
                            case 4: option_4(ptr);
                                    break;
                            case 5: break;
                           default: printf("Invalid input");
                    }
            }
            else
            { int *ptr = data_2;
                    switch(option)
                    {   case 0: option_0(ptr);
                                    break;
                            case 1: option_1(ptr);
                                    break;
                            case 2: option_2(ptr);
                                    break;
                            case 3: option_3(ptr);
                                    break;
                            case 4: option_4(ptr);
                                    break;
                            case 5: break;
                           default: printf("Invalid input");
                    }
            }
    }
return EXIT_SUCCESS;
 }

 /*I have not yet written the code for these functions since I am still 
   working on the main part right now. The only one I defined is option 3 
   which adds an element to the end of the array the user decided to select.*/

 int option_0(int ptr[])
{
    return(0);
}

 int option_1(int ptr[])
{
    return(0);
}

 int option_2(int ptr[])
{
    return(0);
}

//add element to the end of array
int option_3(int ptr[])
{
    int i, value;
    int num_elements = sizeof(ptr)/sizeof(ptr[0]);
    /*printf("num_elements = %d", num_elements);

    printf("Enter number to add: ")
    scanf("%d", &value);

    ptr[num_elements] = value;
    */
    for (i = 0; i > num_elements; i++)
    {
            printf(" %d ",ptr[i]);
    }
 return 1;
 }

  int option_4(int ptr[])
 {
    int i = 0;
    return i;
 }

При компиляции и запуске:

 Program written by: KELSEY WILLIAMS 

 Program compiled on May  1 2018 at 04:54:01.

 Here is what data set 1 looks like now:


 [1]    [2]    [3]    [4]    [5]  

  4      7      6      32      5   

 Here is what data set 2 looks like now:


 [1]    [2]    [3]    [4]    [5]  

  98     47     26     99     187   
 Which set do you want to update [1 or 2]: 
 1

 Displaying options for data set 1...

 DATA CONFIRMATION AND UPDATE PROGRAM


 1. Display data set now.

 2. Delete an entry from the data set.

 3. Add an entry to the end of the data set.

 4. Change an existing entry.

 5. Quit this program.

 Enter choice [ 1-5, 0 = change data set]:
 3
 you selected option: [3]

 option = 3choice = 1 option: 3choice: 1 option: 3choice: 1 option: 
 3choice: 1 option: 3choice: 1 option: 3choice: 1 option: 3choice: 1 option: 
 3choice: 1 option: 3choice: 1 option: 3choice: 1 option: 3choice: 1 option: 
 3choice: 1 and on and on and on....=(

Спасибо за любую помощь заранее.

Ответы [ 2 ]

0 голосов
/ 01 мая 2018

Чтобы заново создать ошибку, я попробовал ваш фрагмент кода в моей IDE с Main(), вызвав choice_list(), который выполнил нормально.

Я также попытался отладить с точкой останова, и она не попала в цикл

enter image description here

Поэтому я считаю, что оставшаяся часть фрагмента кода, которая не была обновлена ​​в вашем вопросе, вызывает бесконечный цикл.

Кроме того, если вы уделите пристальное внимание форматированию сообщения внутри бесконечного цикла, вы заметите, что это другой раздел кода, вызывающий цикл.

choice: 1 option: 3choice: 1 option: 3choice: 1 option: 3

P.S : Хотя это не может быть окончательным решением, но надеюсь, что это укажет вам правильное направление. Я могу попытаться помочь вам лучше, если вы разместите соответствующие фрагменты кода

0 голосов
/ 01 мая 2018

Причиной здесь является функция scanf ()
scanf () где-то в вашей программе получает какой-то ввод, отличный от цифр (десятичных разрядов), например, символов, символов или escape-последовательности, что является причиной бесконечного цикла.

Решение очистите буфер ввода scanf () перед получением ввода, используйте приведенный ниже фрагмент кода в цикле перед вызовом функции scanf () в подпрограмме choice_list (), а также в функции main ().

[1]/* clears the input buffer */
while ((getchar()) != '\n');  

как в подпрограмме choice_list ()

...
...
while (!(0 == option || 1 == option || 2 == option || 3 == option || 4 == option || 5 == option))
{
    printf("\nInvalid Entry, please enter [0-5]: ");
   /* clears the input buffer */
    while ((getchar()) != '\n');  
    scanf("%d", &option);
}
...
...

аналогично, если вы использовали scanf () в цикле, сначала очистите входной буфер, используя код выше [1], прежде чем вызывать функцию scanf (). Для получения дополнительной информации см. Справочную страницу scanf ().

...