gotoとラベルを使用してこのプログラムをナビゲートしようとしていますが、プログラムをナビゲートすると結果が期待通りにはなりません。C - ルーピング/ gotoを使用したナビゲーション
プログラムを読み込むときに、クラスの生徒数を入力するように求められます。数値以外の値を入力すると、値が再入力されます。しかし、それはプログラムを通して進行し続けるようです。数値を入力すると、プログラムの残りの部分は通常どおり進められます。しかし、それは同様にループを続けるようです。最後に、私のコンパイラが提供するエラー/警告はありません。
質問:私のコードには誤りがありますか?私がやろうとしていることを達成するためのより良い方法はありますか?手続き型/単純化型アプローチを使用するのではなく、関数とwhileループを使用してプログラムを書き直すほうが賢明でしょうか。
プログラム:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int areStudents;
struct Student
{
int id;
char name[50];
char address[50];
char phone[20];
};
int main()
{
char userInput1, userInput2, currentName[50], currentAddress[50], currentPhone[20];
begining:
printf("\nEnter the number of students in the class: ");
scanf("%c", &userInput1);
if(!isdigit(userInput1))
{
printf("\nThe input you selected was not valid. Please enter another option\n");
//userInput1 = '0';
goto begining;
} else if(isdigit(userInput1)){
// asks users to input P, E, H
struct Student student[userInput1];
label1:
printf("=>Press P to print the list\n\n=>Press E to enter the student data\n\n=>Press H For help\nPlease enter your selection: ");
scanf("%c", &userInput2);
switch(userInput2) // switch for choices P, E, and H
{
case 'p':
case 'P':
if(areStudents != 1)
{
printf("\n**You have not set any student variables. Please set them before using this option**\n\n");
goto label1;
} else {
// print the list of student info
for(int i=0; i>=userInput1; i++)
{
student[i].id = i+1;
printf("\nStudent %d name is: %s", i+1, student[i].name);
printf("\nStudent %d address is: %s", i+1, student[i].address);
printf("\nStudent %d phone number is: %s", i+1, student[i].phone);
}
break;
}
case 'e':
case 'E':
for(int j=0; j>=userInput1; j++)
{
student[j].id = j+1;
printf("\nStudent %d name is: ", j+1);
scanf("%s", currentName);
strcpy(student[j].name, currentName);
printf("\nStudent %d address is: ", j+1);
scanf ("%s", currentAddress);
strcpy(student[j].address, currentAddress);
printf("\nStudent %d phone number is: ", j+1);
scanf("%s", currentPhone);
strcpy(student[j].phone, currentPhone);
}
areStudents = 1;
goto label1;
case 'h':
case 'H':
printf("Select E or e to enter the data entry mode.\n\nAfter you have entered all your data, you can print the data by entering p or P.\n\nYou can only print after entering your data... otherwise, you will see some garbage values.");
default:
goto label1;
}
}
return(0);
}
結果(非数値):
Enter the number of students in the class: d
The input you selected was not valid. Please enter another option
Enter the number of students in the class:
The input you selected was not valid. Please enter another option
Enter the number of students in the class:
結果(数値):の
Enter the number of students in the class: 3
=>Press P to print the list
=>Press E to enter the student data
=>Press H For help
Please enter your selection: =>Press P to print the list
=>Press E to enter the student data
=>Press H For help
Please enter your selection:
*手続き型/単純化型アプローチを使用するのではなく、関数とwhileループを使用してプログラムを書き直す方がよいでしょうか? –