C++ 在循环中向用户询问信息:如何保持用户想要的工作次数?
我正在做一个关于工资单的节目,我被卡住了。在程序中,在用户输入员工数量后,我必须进行循环,允许用户输入每个员工的信息。然后输入的数据将存储在我制作的employees数组中。我试图解决我的问题,因为我的计划中有多少员工C++ 在循环中向用户询问信息:如何保持用户想要的工作次数?,c++,loops,C++,Loops,我正在做一个关于工资单的节目,我被卡住了。在程序中,在用户输入员工数量后,我必须进行循环,允许用户输入每个员工的信息。然后输入的数据将存储在我制作的employees数组中。我试图解决我的问题,因为我的计划中有多少员工MAXSIZE,并删除内部if子句,其中有几个问题: 1-在while循环中的某个地方放置一个i++ 为什么不使用for循环呢 2-名称和标题可能应该是字符串: #include <string> //in the main: std:string name; 3-w
#include <iostream>
using namespace std;
const int MAXSIZE = 20;
struct EmployeeT
{
char name[MAXSIZE];
char title;
double gross;
double tax;
double net;
};
EmployeeT employees[MAXSIZE];
int main()
{
cout << "How many Employees? ";
int numberOfEmployees;
cin >> numberOfEmployees;
while(numberOfEmployees > MAXSIZE)
{
cout << "Error: Maximum number of employees is 20\n";
cout << "How many Employees? ";
cin >> numberOfEmployees;
}
int name;
int title;
double gross;
double tax;
double net;
for (int count=0; count<numberOfEmployees; count++)
{
cout << "Name: \n";
cin >> employees[ count ].name;
cout << "Title: \n";
cin >> employees[ count ].title;
cout << "Gross: \n";
cin >> employees[ count ].gross;
cout << "Tax: \n";
cin >> employees[ count ].tax;
cout << "Net: ";
cin >> employees[ count ].net;
}
}
我刚刚更新到这个。我的最后一个问题是,如何让第二个循环保持用户想要的工作次数。对于用户在?中输入的尽可能多的员工,您需要这样的内容: UPD:对于第一个循环,您可以将条件更改为numberOfEmployees>MAXSIZE,并删除内部if子句,其中有几个问题: 1-在while循环中的某个地方放置一个i++ 为什么不使用for循环呢 2-名称和标题可能应该是字符串:
#include <string>
//in the main:
std:string name;
3-while条件应为:
while(i<numberOfEmployees && i<MAXSIZE)
编辑:我看你刚刚纠正了那个
编辑:我只是注意到你总是写相同的变量。改为写信给员工[i]。姓名等
这解决了您的问题吗?第一个循环,当您检查用户输入的值是否过大时,它永远不会结束!使用while numberOfEmployees>MAXSIZE并跳过if而不是if中的内容,而不是while true 另外,由于已经确保numberofemployees有效,因此在第二个循环中不需要&&i
}在这个循环之前,我实际上还有一个while循环。当我尝试运行程序时,第一个while循环工作,但是程序退出,而第二个while循环不工作。是的,它工作了。现在,两个循环都可以工作了,但是在第二个循环中,当它要求输入名称并且我输入了一个名称后,程序退出了。。。对不起,你是说我用numberOfEmployees太多了吗?哦,对不起,哈哈。我改变了我的计划。现在看看。再次感谢,看起来更像;-别忘了用绿色勾选标记解决问题的答案。我的最后一个问题是,如何让第二个循环继续工作,以满足用户的需要。对于用户输入的员工数量?
numberOfEmployees = numberOfEmployees <= MAXSIZE ? numberOfEmployees : MAXSIZE;
for(int i = 0; i < numberOfEmployees; i++) { ... }
#include <string>
//in the main:
std:string name;
while(i<numberOfEmployees && i<MAXSIZE)
for (int count=0; count<numberOfEmployees; count++)
{
cout << "Name: \n";
cin >> employees[ count ].name;
cout << "Title: \n";
cin >> employees[ count ].title;
cout << "Gross: \n";
cin >> employees[ count ].gross;
cout << "Tax: \n";
cin >> employees[ count ].tax;
cout << "Net: ";
cin >> employees[ count ].net;
//Ask user if he wants to add more employees, if no break the loop else iterate again
cout<<"Do u want to continue: 1 to continue 0 to exit");
cin>>flag;
if(flag==0)
break;
}