How to get rid of goto statement in this program and end the flip:>>>?
int main()
{
int array[10];
int sum = 0;
int desending;
int mul = 1;
float avg = 10;
int option;
do
{
flip1:
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
flip2:
if (option == 1)
{
int h = 1;
int i;
for (i = 0; i < 10; i++)
{
cout << h << " Enter the Numbers ";
cin >> array[i];
sum = sum + array[i];
mul = mul*array[i];
h++;
}
system("cls");
for (int j = 0; j < 10; j++)
{
cout << "Given numbers" << j << " = " << array[j] << "\n";
}
avg = sum / avg;
int max = array[0];
int min = array[0];
for (int i = 0; i < 10; i++)
{
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
cout << "\nSum of the Numbers= 4" << sum << endl;
cout << "\nProduct of the Numbers is = " << mul << endl;
cout << "\nThe Avg of Numbers is = " << avg << endl;
cout << "\nmaximum of the Numbers is = " << max << endl;
cout << "\nminimum of the Numbers is = " << min << endl;
}
else if (option == 2)
{
int array[10], o, index = -1;
cout << "enter the elements of array" << endl;
for (o = 0; o < 10; o++)
{
cin >> array[o];
}
system("cls");
int p;
cout << "enter value to find" << endl;
cin >> p;
for (int c = 0; c < 10; c++)
{
if (array[c] == p)
index = c;
}
system("cls");
if (index == -1)
{
cout << "no value found" << endl;
}
else
cout << "Value found at\t" << index << endl;
}
else if (option == 3)
{
system("cls");
int a[10], r, t, temp;
cout << "Enter the array elements: " << endl;
for (r = 0; r<10; ++r)
cin >> a[r];
system("cls");
for (r = 0; r<10; ++r)
for (t = 0; t<9; t++)
if (a[r]<a[t])
{
temp = a[r];
a[r] = a[t];
a[t] = temp;
}
cout << "Array after sorting: " << endl;
for (r = 0; r<10; r++)
cout << a[r] << "\t ";
}
cout << "\nplease select an option\n" << endl;
cout << "press m for main menue" << endl;
cout << "press r for repeat" << endl;
cout << "press e for exit" << endl;
char q;
cin >> q;
if (q == 'm')
{
system("cls");
goto flip1;
}
if (q == 'r')
{
system("cls");
goto flip2;
}
if (q == 'e')
{
return 0;
}
} while (option != 4);
return 0;
}
You can refer the below code.
Before entering the loop.
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
do {
if (option == 1)
{
int h = 1;
int i;
for (i = 0; i < 10; i++)
{
/* All text as same */
At the end: change
if (q == 'm')
{
system("cls");
goto flip1;
}
if (q == 'r')
{
system("cls");
goto flip2;
}
if (q == 'e')
{
return 0;
}
To.
if (q == 'e')
{
return 0;
}
system("cls");
if (q == 'm')
{
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
}
PS: You can also create a function that prints the menu, get input from user and return the same.
If you divide your code into chunks of cohesive functionality, you can put them into their own functions and the main function can be much simpler. Here's my recommendation:
#include <iostream>
#include <cstdlib>
using namespace std;
int getOption1()
{
int option;
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
return option;
}
char getOption2()
{
char option;
cout << "\nplease select an option\n" << endl;
cout << "press m for main menue" << endl;
cout << "press r for repeat" << endl;
cout << "press e for exit" << endl;
cin >> option;
return option;
}
void doArrayBasics()
{
int array[10];
int sum = 0;
float avg = 10;
int mul = 1;
int h = 1;
int i;
for (i = 0; i < 10; i++)
{
cout << h << " Enter the Numbers ";
cin >> array[i];
sum = sum + array[i];
mul = mul*array[i];
h++;
}
system("cls");
for (int j = 0; j < 10; j++)
{
cout << "Given numbers" << j << " = " << array[j] << "\n";
}
avg = sum / avg;
int max = array[0];
int min = array[0];
for (int i = 0; i < 10; i++)
{
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
cout << "\nSum of the Numbers= 4" << sum << endl;
cout << "\nProduct of the Numbers is = " << mul << endl;
cout << "\nThe Avg of Numbers is = " << avg << endl;
cout << "\nmaximum of the Numbers is = " << max << endl;
cout << "\nminimum of the Numbers is = " << min << endl;
}
void doArraySearching()
{
int array[10];
int o;
int index = -1;
cout << "enter the elements of array" << endl;
for (o = 0; o < 10; o++)
{
cin >> array[o];
}
system("cls");
int p;
cout << "enter value to find" << endl;
cin >> p;
for (int c = 0; c < 10; c++)
{
if (array[c] == p)
index = c;
}
system("cls");
if (index == -1)
{
cout << "no value found" << endl;
}
else
cout << "Value found at\t" << index << endl;
}
void doArraySorting()
{
system("cls");
int a[10];
int r;
int t;
int temp;
cout << "Enter the array elements: " << endl;
for (r = 0; r<10; ++r)
cin >> a[r];
system("cls");
for (r = 0; r<10; ++r)
for (t = 0; t<9; t++)
if (a[r]<a[t])
{
temp = a[r];
a[r] = a[t];
a[t] = temp;
}
cout << "Array after sorting: " << endl;
for (r = 0; r<10; r++)
cout << a[r] << "\t ";
}
int main()
{
int option1;
char option2 = 'r';
do
{
if ( option2 == 'r' )
{
option1 = getOption1();
}
switch (option1)
{
case 1:
doArrayBasics();
break;
case 2:
doArraySearching();
break;
case 3:
doArraySorting();
break;
case 4:
break;
default:
cout << "Invalid option " << option1 << endl;
}
if ( option1 != 4 )
{
option2 = getOption2();
}
} while (option1 != 4 && option2 != 'e' );
return 0;
}
You can use an inner loop to remove all gotos.
Remove flip1:, change flip2: to do {. The loop should begin like that:
do
{
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
do
{
if (option == 1)
{
At the end of the loop, change:
if (q == 'm')
{
system("cls");
goto flip1;
}
if (q == 'r')
{
system("cls");
goto flip2;
}
if (q == 'e')
{
return 0;
}
to :
if (q == 'e')
{
return 0;
}
system("cls");
} while (q == 'r');
Breaking your code into functions will also make it more readable but is not mandatory to remove gotos.
caveat: the following code not tested
int main()
{
int array[10];
int sum = 0;
int desending;
int mul = 1;
float avg = 10;
int option;
int done = 0;
int looping = 1;
while( !done )
{
cout << "\n\t\t------------------------------------------------" << endl;
cout << "\t\tlllllllll Menue lllllllllll" << endl;
cout << "\t\tlllllllll 1. Array Basics lllllllllll" << endl;
cout << "\t\tlllllllll 2. Searching Array lllllllllll" << endl;
cout << "\t\tlllllllll 3. Sorting Array lllllllllll" << endl;
cout << "\t\tlllllllll 4. Exit lllllllllll" << endl;
cout << "\t\t------------------------------------------------\n" << endl;
cout << "Please select an option" << endl;
cin >> option;
system("cls");
while( looping )
{
looping = 0;
switch( option )
{
case 1:
int h = 1;
int i;
for (i = 0; i < 10; i++)
{
cout << h << " Enter the Numbers ";
cin >> array[i];
sum = sum + array[i];
mul = mul*array[i];
h++;
}
system("cls");
for (int j = 0; j < 10; j++)
{
cout << "Given numbers" << j << " = " << array[j] << "\n";
}
avg = sum / avg;
int max = array[0];
int min = array[0];
for (int i = 0; i < 10; i++)
{
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
cout << "\nSum of the Numbers= 4" << sum << endl;
cout << "\nProduct of the Numbers is = " << mul << endl;
cout << "\nThe Avg of Numbers is = " << avg << endl;
cout << "\nmaximum of the Numbers is = " << max << endl;
cout << "\nminimum of the Numbers is = " << min << endl;
break;
case 2:
int array[10], o, index = -1;
cout << "enter the elements of array" << endl;
for (o = 0; o < 10; o++)
{
cin >> array[o];
}
system("cls");
int p;
cout << "enter value to find" << endl;
cin >> p;
for (int c = 0; c < 10; c++)
{
if (array[c] == p)
index = c;
}
system("cls");
if (index == -1)
{
cout << "no value found" << endl;
}
else
cout << "Value found at\t" << index << endl;
break;
case 3:
system("cls");
int a[10], r, t, temp;
cout << "Enter the array elements: " << endl;
for (r = 0; r<10; ++r)
cin >> a[r];
system("cls");
for (r = 0; r<10; ++r)
{
for (t = 0; t<9; t++)
{
if (a[r]<a[t])
{
temp = a[r];
a[r] = a[t];
a[t] = temp;
}
}
}
cout << "Array after sorting: " << endl;
for (r = 0; r<10; r++)
cout << a[r] << "\t ";
break;
case 4:
done = 1;
break;
default:
cout << "\nplease select an option\n" << endl;
cout << "press m for main menue" << endl;
cout << "press r for repeat" << endl;
cout << "press e for exit" << endl;
char q;
cin >> q;
switch( q )
{
case 'm':
system("cls");
// looping already set = 0
break;
case 'r':
system("cls");
looping = 1;
break;
case 'e':
done = 1;
break;
default:
break;
} // end switch
break;
} // end switch
} // end while looping
} // end while not done
return 0;
} // end function: main
Related
Good day, I'm having difficulty on the last two parts of my program where it's supposed to only output players who got maximum/minimum scores, I need help on how to do it because I'm really confused. If it's also alright to provide some explanations I'd really appreciate it.
I tried this approach:
#include <iostream>
using namespace std;
int main() {
double lrgst, lrgst2, lrgst3;
int numbers[5];
lrgst = lrgst2 = lrgst3;
for (int i = 0; i < 5; i++) {
cin >> numbers[i];
}
for (int i = 0; i < 5; i++) {
if (numbers[i] > lrgst) {
lrgst3 = lrgst2;
lrgst2 = lrgst;
lrgst = numbers[i];
} else if (numbers[i] > lrgst2) {
lrgst3 = lrgst2;
lrgst2 = numbers[i];
} else if (numbers[i] > lrgst3) {
lrgst3 = numbers[i];
}
}
cout << "largest are: " << lrgst << " " << lrgst2 << " " << lrgst3;
}
this is my actual code:
#include <iostream>
using namespace std;
struct playerdata {
char name[50];
int age, score1, score2;
double average;
};
int main() {
int choice, i = 1, j = 1, z = 1, backtomain2;
char backtomain;
playerdata p1[10];
do {
for (int a = 0; a < 47; a++) {
cout << "=";
}
cout << "\n";
for (int b = 0; b < 22; b++) {
cout << " ";
if (b == 21) {
cout << "MENU \n";
}
}
for (int c = 0; c < 47; c++) {
ocut << "=";
}
cout << " "
"\n1. Add record\n"
"2. View players records\n"
"3. Compute for the average\n"
"4. Show the player(s) who gets the max average.\n"
"5. Show the player(s) who gets the min average.\n"
"6. Exit\n"
"Enter your choice:";
cin >> choice;
if (choice == 1) {
cout << "Add player data" << endl;
do {
cout << "Enter player " << i << " nickname:";
cin >> p1[i].name;
cout << "Enter player " << i << " age:";
cin >> p1[i].age;
cout << "Enter player " << i << " score 1:";
cin >> p1[i].score1;
cout << "Enter player " << i << " score 2:";
cin >> p1[i].score2;
cout << "Enter again? (Y/N)";
cin >> backtomain;
i++;
}
while (backtomain != 'N' && backtomain != 'n' && i < 7);
if (choice == 2) {
cout << "Player records" << endl;
cout << "Player nickname "
<< "Player age "
<< " player score 1"
<< "
player score 2\n ";
for (z = 1; z <= i - 1; z++) {
cout << p1[z].name << " " << p1[z].age << "" << p1[z].score1 << ""
<< p1[z].score2 << "\n";
}
cout << "Press 1 to go back to main menu\n";
cin >> backtomain;
}
if (choice == 3) {
cout << "Computing for average...\n";
for (int d = 1; d <= i - 1; d++) {
p1[d].average = (p1[d].score1 + p1[d].score2) / 2.0;
cout << "\n" << p1[d].average << "\n";
}
cout << "Press 1 to go back to main menu\n";
cin >> backtomain;
}
if (choice == 4) {
cout << "Player(s) who got the max average:\n";
cout << "\nPress 1 to go back to main menu";
cin >> backtomain;
}
if (choice == 5) {
cout << "player(s) who got the min average: \n";
cout << "Press 1 to go back to main menu";
cin >> backtomain;
}
}
while (choice != 6);
}
You can simply sort the array of players for that
int n = sizeof(p1)/ sizeof(p1[0]);
sort(p1, p1+n, compPlayer);
//larget at pl[0]
//smallest at pl[9]
where
bool compPlayer(playerdata p1, playerdata p2) {
return (p1.score1+p1.score2) > (p2.score1+p2.score2);
//use score incase average has not been calculated for all players yet
}
I want to make a Student achievement management system.
The other funtions are right. But the Sorting function always has a little problem. The first row is all 0. the sorting funtion will display the first line with all 0
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
class student
{
int num;
char name[20];
char class1[20];
float Chinese;
float math;
float English;
float aver;//平均成绩
public:
void set()
{
cout << "\t学生学号:";
cin >> num;
cout << "\t学生姓名:";
cin >> name;
cout << "\t学生班级:";
cin >> class1;
cout << "\t语文成绩:";
cin >> Chinese;
cout << "\t英语成绩:";
cin >> English;
cout << "\t数学成绩:";
cin >> math;
}
void show()
{
cout << "该学生的学号:" << num << endl;
cout << "该学生的姓名:" << name << endl;
cout << "该学生的班级:" << class1 << endl;
cout << "该学生的语文成绩:" << Chinese << endl;
cout << "该学生的数学成绩:" << math << endl;
cout << "该学生的英语成绩:" << English << endl;
}
friend void show();
friend void search();
friend void change();
friend void add();
friend void sort();
friend void del();
};
void input();
void show();
void search();
void change();
void add();
void sort();
void del();
student s[100];
int n = 0;
int main()
{
int select;
while (1)
{
system("cls");
cout << "\t ******************欢迎使用******************\n";
cout << "\t **************学生成绩管理系统**************\n";
cout << "\t *------------------------------------------*\n";
cout << "\t * 1——录入学生信息 *\n";
cout << "\t * 2——显示学生信息 *\n";
cout << "\t * 3——查询学生信息 *\n";
cout << "\t * 4——修改学生信息 *\n";
cout << "\t * 5——添加学生信息 *\n";
cout << "\t * 6——排序学生信息 *\n";
cout << "\t * 7——删除学生信息 *\n";
cout << "\t * 0——退出 *\n";
cout << "\t *------------------------------------------*\n";
cout << "\t 你要输入的编号是(0--7):";
cin >> select;
if (select == 0) break;
switch (select) {
case 1:
input(); //调用input函数录入数据
system("pause");
break;
case 2:
show(); //调用show函数显示学生信息
system("pause");
break;
case 3:
search(); //调用search函数查询学生信息
system("pause");
break;
case 4:
change(); //调用change函数修改学生信息
system("pause");
break;
case 5:
add(); //调用add函数添加学生信息
system("pause");
break;
case 6:
paixu(); //调用add函数添加学生信息
system("pause");
break;
case 7:
del(); // 调用del函数删除学生信息
system("pause");
break;
system("pause");
default:
cout << "没有此选项,请重新选择!" << endl;
}
}
return 0;
}
void input() //录入学生信息的函数
{
char sel;
do
{
n++;
cout << "\t请输入第" << n << "个学生信息:\t" << endl;
s[n].set();
cout << "是否要继续录入学生信息(Y/N):";
cin >> sel;
} while (sel == 'Y' || sel == 'y');
}
void show()
{
cout << left; //设置输出左对齐
cout << setw(10) << "学生学号"
<< setw(10) << "学生姓名"
<< setw(13) << "学生班级"
<< setw(12) << "语文成绩"
<< setw(12) << "数学成绩"
<< setw(12) << "英语成绩"
<< endl;
for (int i = 1; i <= n; i++)
{
cout << setw(10) << s[i].num
<< setw(10) << s[i].name
<< setw(13) << s[i].class1
<< setw(12) << s[i].Chinese
<< setw(12) << s[i].math
<< setw(12) << s[i].English << endl;
}
cout << endl;
}
void search()//查询
{
int a, b, i; char c[20];
cout << "请选择查询方式:" << endl;
cout << "按学生姓名查询请按1" << endl;
cout << "按学生学号查询请按2" << endl;
cin >> a;
switch (a)
{
case 1:
{char sel;
do {
cout << "请输入你要查的学生的姓名:" << endl;
cin >> c;
for (i = 1; i <= n; i++)
if (strcmp(s[i].name, c) == 0)
{
cout << "你要查的学生信息为:" << endl;
cout << "学生学号:" << s[i].num << endl << "学生姓名:"
<< s[i].name << endl << "学生班级:"
<< s[i].class1 << endl << "语文成绩:"
<< s[i].Chinese << endl << "数学成绩:"
<< s[i].math << endl << "英语成绩:"
<< s[i].English << endl;
break;
}
else if (strcmp(s[i].name, c) != 0 && i == n)
{
cout << "没有这个学生!" << endl; break;
}
cout << "是否要继续查询学生信息(Y/N):";
cin >> sel;
} while (sel == 'Y' || sel == 'y');
break;
}
case 2:
{ char sel;
do {
cout << "请输入你要查的学生的学号:" << endl;
cin >> b;
for (i = 1; i <= n; i++)
if (s[i].num == b)
{
cout << "你要查的学生信息为:" << endl;
cout << "学生学号:" << s[i].num << endl << "学生姓名:"
<< s[i].name << endl << "学生班级:"
<< s[i].class1 << endl << "语文成绩:"
<< s[i].Chinese << endl << "数学成绩:"
<< s[i].math << endl << "英语成绩:"
<< s[i].English << endl;
break;
}
else if (s[i].num != b&&i == n)
{
cout << "没有这个学生!请核对后再输入!" << endl; break;
}
cout << "是否要继续查询学生信息(Y/N):";
cin >> sel;
} while (sel == 'Y' || sel == 'y');
break; }
default:
cout << "您的输入有误!" << endl;
}
}
void change()
{
{ char sel;
int d, i, e, f, g = 0;
do {
cout << "请输入你要修改的学生的学号:" << endl;
cin >> d;
for (i = 1; i <= n; i++)
if (s[i].num == d)
{
cout << "你要修改的学生信息为:" << endl;
cout << "学生学号:" << s[i].num << endl << "学生姓名:"
<< s[i].name << endl << "学生班级:"
<< s[i].class1 << endl << "语文成绩:"
<< s[i].Chinese << endl << "数学成绩:"
<< s[i].math << endl << "英语成绩:"
<< s[i].English << endl;
e = 1;
break;
}
else if (s[i].num != d&&i == n)
{
cout << "没有这个学生!请核对后再输入!" << endl;
e = 0; break;
}
while (e == 1)
{
{cout << "请输入该学生要修改的信息对应的数字:" << endl;
cout << "学生学号:1"
<< '\t' << "学生姓名:2"
<< '\t' << "学生班级:3"
<< '\t' << "语文成绩:4"
<< '\t' << "数学成绩:5"
<< '\t' << "英语成绩:6" << endl;
}
cin >> f;
switch (f)
{
case 1:cout << "\t新的学生学号为:";
cin >> s[i].num; break;
case 2:cout << "\t新的学生姓名为:";
cin >> s[i].name; break;
case 3:cout << "\t新的学生班级为:";
cin >> s[i].class1; break;
case 4:cout << "\t新的语文成绩为:";
cin >> s[i].Chinese; break;
case 5:cout << "\t新的数学成绩为:";
cin >> s[i].math; break;
case 6:cout << "\t新的英语成绩为:";
cin >> s[i].English; break;
default:cout << "您的输入有误,请重新输入!";
cin >> f;
}
e = 0;
g = 1;
}
if (g == 1)
{
cout << "修改成功!";
}
cout << "是否要继续修改学生信息(Y/N):";
cin >> sel;
} while (sel == 'Y' || sel == 'y');
}
}
void add()
{
char sel;
do
{
n++;
cout << "\n请输入第" << n << "个学生信息:\n";
cout << "\t学生学号:";
cin >> s[n].num;
cout << "\t学生姓名:";
cin >> s[n].name;
cout << "\t学生班级:";
cin >> s[n].class1;
cout << "\t语文成绩:";
cin >> s[n].Chinese;
cout << "\t数学成绩:";
cin >> s[n].math;
cout << "\t英语成绩:";
cin >> s[n].English;
cout << "是否要继续添加学生信息(Y/N):";
cin >> sel;
} while (sel == 'Y' || sel == 'y');
}
void sort()
{
student w;
for (int i = 0; i<n - 1; i++)
for (int j = 0; j<n - 1-i; j++)
if (s[j].aver < s[j + 1].aver)
{
w = s[j]; s[j] = s[j + 1]; s[j + 1] = w;
}
cout << "按平均成绩排序结果:" << endl;
cout << left; //设置输出左对齐
cout << setw(10) << "学生学号"
<< setw(10) << "学生姓名"
<< setw(13) << "学生班级"
<< setw(12) << "语文成绩"
<< setw(12) << "数学成绩"
<< setw(12) << "英语成绩"
<< setw(12) << "平均成绩"
<< endl;
for (int k = 0; k <n ; k++)
{
s[k].aver = (s[k].math + s[k].Chinese + s[k].English) / 3;
cout << setw(10) << s[k].num
<< setw(10) << s[k].name
<< setw(13) << s[k].class1
<< setw(12) << s[k].Chinese
<< setw(12) << s[k].math
<< setw(12) << s[k].English
<< setw(12) << s[k].aver << endl;
}
}
void del()
{
int j, i, k; char c[10], sel, y;
do {
cout << "请输入你要删除的学生的姓名:" << endl;
cin >> c;
for (i = 1; i <= n; i++)
if (strcmp(s[i].name, c) == 0)
{
cout << "你要删除的学生信息为:" << endl;
cout << "学生学号:" << s[i].num << endl
<< "学生姓名:" << s[i].name << endl
<< "学生班级:" << s[i].class1 << endl
<< "语文成绩:" << s[i].Chinese << endl
<< "数学成绩:" << s[i].math << endl
<< "英语成绩:" << s[i].English << endl;
cout << "确认删除?(y/n):";
cin >> y;
if (y == 'Y' || y == 'y')
{
for (j = i; j <= n + 1; j++)
{
s[j] = s[j + 1];
} k = 1;
}
else
cout << "删除失败!" << endl;
break;
}
else if (strcmp(s[i].name, c) != 0 && i == n)
{
cout << "没有这个学生!请核对后再输入!" << endl;
k = 0; break;
}
while (k == 1)
{
if (y == 'Y' || y == 'y')
cout << "删除成功!";
n--;
k = 0;
}
cout << "是否要继续删除学生信息(Y/N):";
cin >> sel;
} while (sel == 'Y' || sel == 'y');
}
In your add function, you increment n before using it as an index into your s array. This leaves s[0] empty (so you have a row of all zeros), and s[n] with the last entry (so it won't be included in the sort).
Store all your inputs in add, then increment n.
I have project in banker algorithm implement in c++
But I have small mistake :') in resource request
I didn't know what the mistake. The first if statement doesn't work :(
#include<iostream>
#include<vector>
using namespace std;
int main() {
int work[4];
int allocation[5][4];
int max[5][4];
int need[5][4];
int p, pr, r, a, aval[4], req[4];
bool state[5], test;
vector < int > avl;
//----------------------------------------
test = true;
for (int i = 0; i < 4; i++)
work[i] = aval[i];
for (int i = 0; i < 5; i++)
state[i] = false;
//----------------------------enter p r---------------------------------
cout << "Enter the number of processes in the system :";
cin >> p;
cout << "\nEnter the number of recourses :";
cin >> r;
//---------------------enter alloc---
cout << "\nEnter the allocation " << endl;
if (r = 1)
{
cout << "\t A \n \t ";
}
else if (r = 2)
{
cout << "\t A B \n \t ";
}
else if (r = 3)
{
cout << " A B C\n \t ";
}
else if (r = 4)
{
cout << " A B C D\n \t ";
}
for (int i = 0; i < p; i++)
{
cout << endl << "\t" << "P" << i << ":";
for (int j = 0; j < 4; j++)
{
cin >> allocation[i][j];
cout << " ";
}
}
//-----------------------------entet max----------------
cout << "\nEnter the MAX" << endl;
if (r = 1)
cout << " A \n \t ";
else if (r = 2)
cout << " A B \n \t ";
else if (r = 3)
cout << " A B C\n \t ";
else if (r = 4)
cout << " A B C D\n \t ";
for (int i = 0; i < p; i++)
{
cout << endl << "P" << i << ":";
for (int j = 0; j < 4; j++)
{
cin >> max[i][j];
need[i][j] = max[i][j] - allocation[i][j];
}
}
//-----------------enter ava--------------
cout << "\nEnter the avaliable number : " << endl;
for (int i = 0; i < 4; i++)
{
cin >> aval[i];
cout << " ";
}
//-----------------enter request--------------
cout << "\nEnter the number of process want be request : ";
cin >> pr;
cout << "\nEnter the request number : " << endl;
for (int i = 0; i < 4; i++)
{
cin >> req[i];
cout << " ";
}
//-----------------------------------COUT---------------------
cout << endl << "There are " << p << " processes in the system." << endl << endl;
cout << "There are " << r << " resource types." << endl << endl;
//----------------------------------cout allocation---------------
cout << " The allocation Matrix : " << endl << endl;
cout << "\t A B C D";
for (int i = 0; i < p; i++)
{
cout << endl << "\tP" << i << ":";
for (int j = 0; j < 4; j++)
{
cout << allocation[i][j] << " ";
}
cout << endl;
}
//----------------------------------cout max---------------
cout << endl << " The Max Matrix is... " << endl << endl;
cout << "\t A B C D";
for (int i = 0; i < p; i++)
{
cout << endl << "\tP" << i << ":";
for (int j = 0; j < 4; j++)
{
cout << max[i][j] << " ";
}
cout << endl;
}
//-------------------------cout need-------------------------------------------
cout << endl << " The Need Matrix is... " << endl << endl;
cout << "\t A B C D";
for (int i = 0; i < p; i++)
{
cout << endl << "\tP" << i << ":";
for (int j = 0; j < 4; j++)
{
cout << need[i][j] << " ";
}
cout << endl;
}
//----------------------------- cout aval ---------------------
cout << endl << "The Available Vector is..." << endl << endl;
cout << "A B C D" << endl;
for (int i = 0; i < 4; i++)
{
cout << aval[i] << " ";
}
//-----------------------------------SAFE STATE-----------------------
int k = 0;
for (k = 0; k < p; k++) {
if (state[k] == false) {
test = false;
for (int j = 0; j<r; j++) {
if (need[k][j] > work[j])
break;
if (need[k][j] <= aval[j])
test = true;
}
}
}
if (test == true) {
for (int j = 0; j < r; j++)
{
work[j] = work[j] + allocation[k][j];
}
state[k] = true;
cout << endl << endl << "THE SYSTEM IS IN A SAFESTATE!" << endl;
}
if (test == false) {
state[k] = false;
cout << endl << endl << "THE SYSTEM IS NOT IN A SAFE STATE!";
}
//-----------------------------------request------------------------
cout << "\nThe Request Vector is..." << endl;
cout << " A B C D" << endl;
cout << pr << ":";
for (int i = 0; i < 4; i++)
{
cout << req[i] << " ";
}
bool test2 = false;
for (int i = 0; i < p; i++) {
if (pr == p) {
for (int j = 0; j < 4; j++)
{
if (req[j] <= avl[j] && req[j] <= need[i][j])
{
test2 = true;
}
else
{
break;
}
}
if (test2 = true)
{
for (int n = 0; n < r; n++)
{
aval[n] = aval[n] - req[n];
allocation[i][n] = allocation[i][n] + req[n];
need[i][n] = need[i][n] - req[n];
}
cout << "THE REQUEST CAN BE GRANTED!" << endl << endl;
cout << "The Available Vector is...";
cout << "A B C D" << endl;
for (int x = 0; x < r; x++)
{
cout << aval[x] << " ";
}
}
else
{
cout << "THE REQUEST CANNOT BE GRANTED!" << endl << endl;
}
}
}
//------------------------------------------------------------------------------
system("pause");
return 0;
}
When checking if two primitive types are equal, you need to use "==" instead of "="
e.g, change your if statements from
if ( r = 1 )
to
if (r == 1)
Apart from above
work[i] = aval[i]; - aval[i] - has not been initialised
Read up on switch instead of r == 1 do this etc. ( I took into account the above statement and the chained if statements
Ditto with = true. Learn the difference between comparison and assignment
Perhaps learn how to use the debugger
You need to use cout << flush so that the output is sent.
.... I could add others - this is enough to get on with
Here is the whole working program. I made some changes in it and made the code more easy to understand.
int p, r;
bool test;
vector < int > avl;
//----------------------------enter p r---------------------------------
system("clear");
cout << "Enter the number of processes in the system: ";
cin >> p;
cout << "Enter the number of recourses: ";
cin >> r;
//test
int allocation[p][r];
int max[p][r];
int need[p][r];
int aval[r];
int state[p];
test = true;
//test
//---------------------enter alloc---
system("clear");
cout << "\nEnter the allocation " << endl;
if (r == 1)
{
cout << "\t A \n \t ";
}
else if (r == 2)
{
cout << "\t A B \n \t ";
}
else if (r == 3)
{
cout << "\t A B C \n \t ";
}
else if (r == 4)
{
cout << "\t A B C D \n \t ";
}
for (int i = 0; i < p; i++)
{
cout << endl << "\t" << "P" << i << ": ";
for (int j = 0; j < r; j++)
{
cin >> allocation[i][j];
cout << " ";
}
}
system("clear");
//-----------------------------entet max----------------
cout << "\nEnter the MAX" << endl;
if (r == 1)
cout << "\t A \n \t ";
else if (r == 2)
cout << "\t A B \n \t ";
else if (r == 3)
cout << "\t A B C\n \t ";
else if (r == 4)
cout << "\t A B C D\n \t ";
for (int i = 0; i < p; i++)
{
cout << endl << "\t" << "P" << i << ": ";
for (int j = 0; j < r; j++)
{
cin >> max[i][j];
need[i][j] = max[i][j] - allocation[i][j];
}
}
system("clear");
//-----------------enter ava--------------
cout << "\nEnter the avaliable number : " << endl;
cout<<"\tAvail: ";
for (int i = 0; i < r; i++)
{
cin >> aval[i];
cout << " ";
}
//-----------------------------------COUT---------------------
system("clear");
system("clear");
cout << "There are " << p << " processes in the system." << endl;
cout << "There are " << r << " resource types." << endl << endl;
//----------------------------------cout allocation---------------
cout << " The allocation Matrix : " << endl << endl;
if (r == 1)
cout << "\t A \n \t ";
else if (r == 2)
cout << "\t A B \n \t ";
else if (r == 3)
cout << "\t A B C\n \t ";
else if (r == 4)
cout << "\t A B C D\n \t ";
for (int i = 0; i < p; i++)
{
cout << endl << "\tP" << i << ": ";
for (int j = 0; j < r; j++)
{
cout << allocation[i][j] << " ";
}
cout << endl;
}
//----------------------------------cout max---------------
cout << endl << " The Max Matrix is... " << endl << endl;
if (r == 1)
cout << "\t A \n \t ";
else if (r == 2)
cout << "\t A B \n \t ";
else if (r == 3)
cout << "\t A B C\n \t ";
else if (r == 4)
cout << "\t A B C D\n \t ";
for (int i = 0; i < p; i++)
{
cout << endl << "\tP" << i << ": ";
for (int j = 0; j < r; j++)
{
cout << max[i][j] << " ";
}
cout << endl;
}
//-------------------------cout need-------------------------------------------
cout << endl << " The Need Matrix is... " << endl << endl;
for(int i = 0; i < p; i++)
{
for(int j = 0; j < r; j++)
{
need[i][j] = max[i][j] - allocation[i][j];
}
}
if (r == 1)
cout << "\t A \n \t ";
else if (r == 2)
cout << "\t A B \n \t ";
else if (r == 3)
cout << "\t A B C\n \t ";
else if (r == 4)
cout << "\t A B C D\n \t ";
for (int i = 0; i < p; i++)
{
cout << endl << "\tP" << i << ": ";
for (int j = 0; j < r; j++)
{
cout << need[i][j] << " ";
}
cout << endl;
}
//----------------------------- cout aval ---------------------
cout << endl << "The Available Vector is..." << endl << endl;
cout<<"\tAvail: ";
for (int i = 0; i < r; i++)
{
cout << aval[i] << " ";
}
cout<<endl;
//--------SAFESTATE----------SAFESTATE----------SAFESTATE-------------------
int count = p;
cout<<endl;
cout<<"Safe sequence: ";
do{
for(int loop_var = 0; loop_var < p; loop_var++)
{
test = false;
for (int j = 0; j < r; j++) {
if(state[loop_var] == true)
{
break;
}
if(need[loop_var][j] > aval[j])
{
test = false;
state[loop_var] = false;
break;
}
else
{
test = true;
}
}
if((test))
{
count--;
state[loop_var] = true;
for(int sb = 0; sb < r; sb++)
{
aval[sb] = aval[sb] + allocation[loop_var][sb];
}
if(count == 0)
{
cout<<"P"<<loop_var<<" ";
}
else if(count > 0)
{
cout<<"P"<<loop_var<<"-->";
}
}
}
}while(count != 0);
cout<<endl;
//--------SAFESTATE----------SAFESTATE----------SAFESTATE-------------------
cout<<endl;
cout<<"The new available vector is: ";
for(int i = 0; i < r; i++)
{
cout<<aval[i]<<" ";
}
cout << endl << endl;
return 0;
How to do a function that will clean screen and return me to a main menu of program even during entering elements of matrix. And how to disable pressing other keys except arrows and Enter during navigating the menu?
This is my C++ code:
while(running)
{
gotoXY(18,1); cout << "Main Menu";
gotoXY(20,3); cout << " Enter matrix";
gotoXY(20,4); cout << " Randomize matrix";
gotoXY(20,5); cout << " Exit";
system("pause>nul"); // the >nul bit causes it the print no message
if(GetAsyncKeyState(VK_DOWN) || GetAsyncKeyState(VK_RIGHT)) //down button pressed
{
gotoXY(18,pos); cout << " ";
pos++;
gotoXY(18,pos); cout << "->";
menu_item++;
if (pos == 6)
{
gotoXY(18,pos); cout << " ";
pos = 3;
gotoXY(18,3); cout << "->";
menu_item = 0;
}
continue;
}
if(GetAsyncKeyState(VK_UP) || GetAsyncKeyState(VK_LEFT)) //up button pressed
{
gotoXY(18,pos); cout << " ";
pos--;
gotoXY(18,pos); cout << "->";
menu_item--;
if (pos == 2)
{
gotoXY(18,pos); cout << " ";
pos = 5;
gotoXY(18,5); cout << "->";
menu_item = 2;
}
continue;
}
if(GetAsyncKeyState(VK_RETURN)){ // Enter key pressed
switch(menu_item){
case 0: {
gotoXY(20,10);
int i, j, n;
double **a, *b;
cout << "Enter NUMBER of equations: ";
cin >> n;
a = (double **)malloc(n*sizeof(double));
b = (double *)malloc(n*sizeof(double));
cout << "Enter Matrix A\n";
for(i = 0; i < n; i++)
{
a[i] = (double *)malloc(n*sizeof(double));
//Ввод a
for(j = 0; j < n; j++)
{
cout <<"a["<< i + 1 << "][" << j + 1 << "] = ";
//cin >>a[i][j];
a[i][j] = proverkafloat();
}
}
cout << "\tSee input\r\n";
cout << "Matrix A:\r\n";
for(i = 0; i < n; i++)
{
cout << "|\t";
ShowVector(n, a[i]);
};
cout << endl;
cout << "Enter Vector B\n";
for(i = 0; i < n; i++)
{
cout << "b[" << i + 1 << "] = ";
cin >> b[i]
}
cout << "\n\n";
cout << "\tSee input\r\n";
cout << "\n";
cout << "Vector B:\r\n";
cout << "|\t";
ShowVector(n, b);
system("pause");
system("CLS");
gotoXY(18,pos); cout << "->";
break;
}
case 1:
{
gotoXY(20,10);
int i, j;
double **a, *b, n;
cout << "Enter NUMBER of equations: ";
cin >> n;
srand(time(0));
a = (double **)malloc(n*sizeof(double));
b = (double *)malloc(n*sizeof(double));
//Randomizing Matrix A
for(i = 0; i < n; i++)
{
a[i] = (double *)malloc(n*sizeof(double));
//Ввод a
for(j = 0; j < n; j++)
{
a[i][j] = (double)(rand() % 100 + (-50))/((double)(rand() % 100 + (-50)));
}
}
cout << "\tSee input\r\n";
cout << "Matrix A:\r\n";
for(i = 0; i < n; i++)
{
cout << "|\t";
ShowVector(n, a[i]);
};
//Randomizing Vector B
for(i = 0; i < n; i++)
{
b[i] = (double)(rand() % 100 + (-50))/((double)(rand() % 100 + (-50)));
}
cout << "\n\n";
cout << "\tSee input\r\n";
cout << "\n";
cout << "Vector B:\r\n";
cout << "|\t";
ShowVector(n, b);
system("pause");
system("CLS");
gotoXY(18,pos); cout << "->";
break;
}
case 2:
{
gotoXY(20,10);
cout << "The program has now terminated!!";
running = false;
getch();
}
}
}
}
gotoXY(20,21);
return 0;
}
void gotoXY(int x, int y)
{
CursorPosition.X = x;
CursorPosition.Y = y;
SetConsoleCursorPosition(console,CursorPosition);
}
void ShowVector(int n, double * vec)
{
for(int i = 0; i < n; i++)
cout << fixed << setprecision(2) << vec[i] << " ";
cout << "\t";
cout << "|";
cout << "\r\n";
}
The best method to "return" from a canceled menu processing function is to return.
One issue may be stack unwinding. When the main menu processing function calls a function for menu selection process, it pushes the return address on the stack. If the selection processing function fails or needs to return quickly, it can't use a goto because there will still be that return address on the stack. This issue is more pronounced when you have nested menus.
This is similar to error handling and catching. You could try having a catch statement in your main menu function.
I am writing a yahtzee game for my c++ programming class. One of my difficulties I have ran into is the scoring system for different categories. I think I have figured out how to do it for adding 1s, 2s etc but I do not know how to have the program determine when a 3 of a kind, 4 of a kind, etc has been rolled. Here is my code so far.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//Declare variables
int players;
int turn = 1;
vector<string> names;
string playerName;
int dice[5];
int finalScore = 0;
char reroll[5];
char rollDice;
int tries = 1;
const int DICE = 5;
int roll[DICE];
int scorecard;
int scoreThisTurn(int scorecard);
int turnScore = 0;
//Introduction, get number of players.
cout << "Hello, welcome to Yahtzee! How many players are there?" << endl;
cin >> players;
if (players > 4) {
cout << "Sorry, the maximum number of players is 4." << endl;
cout << "How many players are there?" << endl;
cin >> players;
}
//Get player names
string getNames();
for (int i = 0; i < players; i++) {
cout << "Hello player " << i + 1 << ", please enter your name" << endl;
cin >> playerName;
names.push_back(playerName);
}
srand(time(NULL)); //random seed
cout << "Welcome to Yahtzee!\n";
while (turn <= 13) { //roll dice
cout << "Press 'r' to roll" << endl;
cin >> rollDice;
if (rollDice == 'r') {
for (int i = 0; i < DICE; i++) {
roll[i] = rand() % 6 + 1;
}
}
cout << "You rolled: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl;
cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4];
for (int i = 0; i < DICE; i++) {
if (reroll[i] == 'y') {
roll[i] = rand() % 6 + 1;
}
else if (reroll[i] == 'n') {
roll[i];
}
else cout << "Sorry you entered an invalid letter." << endl;
}
cout << "Your second roll is: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl;
cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4];
for (int i = 0; i < DICE; i++) {
if (reroll[i] == 'y') {
roll[i] = rand() % 6 + 1;
}
else if (reroll[i] == 'n') {
roll[i];
}
else cout << "Sorry you entered an invalid letter." << endl;
}
cout << "Your third roll is: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
//displays scorecard categories
cout << "Which category would you like to score this in" << endl;
cout << "1 - ones: " << endl;
cout << "2 - twos: " << endl;
cout << "3 - threes: " << endl;
cout << "4 - fours: " << endl;
cout << "5 - fives: " << endl;
cout << "6 - sixes: " << endl;
cout << "7 - 3 of a kind: " << endl;
cout << "8 - 4 of a kind: " << endl;
cout << "9 - small straight: " << endl;
cout << "10 - large straight: " << endl;
cout << "11 - full house: " << endl;
cout << "12 - yahtzee: " << endl;
cout << "13 - chance: " << endl;
//asks player to choose where to score
cout << "\nEnter 1-14 to choose a category." << endl;
cin >> scorecard;
//assigns points
for (int i = 0; i < DICE; i++) {
turnScore = 0;
if (scorecard == 1) {
if (roll[i] == 1) {
turnScore = turnScore + 1;
}
}
if (scorecard == 2) {
if (roll[i] == 2) {
turnScore = turnScore + 2;
}
}
if (scorecard == 3) {
if (roll[i] == 3) {
turnScore = turnScore + 3;
}
}
if (scorecard == 4) {
if (roll[i] == 4) {
turnScore = turnScore + 4;
}
}
if (scorecard == 5) {
if (roll[i] == 5) {
turnScore = turnScore + 5;
}
}
if (scorecard == 6) {
if (roll[i] == 6) {
turnScore = turnScore + 6;
}
if (scorecard == 7) {
if (roll[i] == 2) {
turnScore = turnScore + 2;
}
}
}
cout << scorecard << endl;
turn++;
}
system("pause");
return 0;
}
As you can see I've set up the scoring for the first 6 categories but don't know how to proceed.
I do not know how to have the program determine when a 3 of a kind, 4 of a kind, etc has been rolled.
Create a variable to help you keep track of the number of dice that have a given number.
int diceCount[DICE] = {0};
and fill up the array with:
for (int i = 0; i < DICE; i++) {
diceCount[roll[i-1]]++
}
Create helper functions to determine whether five, four, or three of a kind have been thrown.
int getNOfAKind(int diceCount[], int N)
{
// This will need moving DICE out of `main`
// making it a global variable.
for ( int i = 0; i < DICE; ++i )
{
if (diceCount[i] == N )
{
return i+1;
}
}
return -1;
}
int getFiveOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 5);
}
int getFourOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 4);
}
int getThreeOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 3);
}
and use it as:
int fiveCount = getFiveOfAKind(diceCount);
if ( fiveCount != -1 )
{
}
int fourCount = getFourOfAKind(diceCount);
if ( fourCount != -1 )
{
}
int threeCount = getThreeOfAKind(diceCount);
if ( threeCount != -1 )
{
}