简体   繁体   English

如何在 C++ 中根据用户输入编写循环?

[英]How to write a loop based on user input in C++?

How do I run a loop based on the user input?如何根据用户输入运行循环?

Example:例子:

I ask how many students does the user want to calculate the grade.我问用户要计算多少学生的成绩。

if the user enters 2 students, then I will ask the user to input grades for exams, homework, quiz etc...如果用户输入 2 个学生,那么我会要求用户输入考试、作业、测验等的成绩...

After the program calculate the first student grade, how do I run the loop again for the second student?程序计算第一个学生成绩后,如何为第二个学生再次运行循环?

I tried using a while loop but it just goes to infinite loop.我尝试使用 while 循环,但它只是进入无限循环。

What I did was:我所做的是:

cout << "number of student you want to calculate grade for" << endl; 

cin >> student; 

while (student) { 
... 
... 
... 
... 
} 

when I run this it goes to infinite loop.当我运行它时,它会进入无限循环。

you need to make sure you decrement student inside the loop as you check if there are any students left to get information for.您需要确保在循环内递减学生,因为您检查是否还有学生要获取信息。

while(student > 0){ // check if any students left
    // your code to get student information
    student -= 1; // decrement students
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM