如何在我的代码中插入循环输入

时间:2014-02-17 19:50:23

标签: c++

所以这是我的代码

#include<iostream>
#include<fstream>

using namespace std;

int main() { 
    int program = 0;
    int score = 0;

    cout << "Enter the number of assignments that were graded. " << endl;
    cin >> program;

    for (int i=1; i <= program; i++)
        cout << "Enter the score for assignment #" << i <<": ";
}

基本上我试图找到一种方法,允许用户输入他们的分数以及cout << Enter the score for assignment #"

基本上我希望编译器这样做(例子):

Enter the number of assignments that were graded: 3   
Enter the score for assignment #1: 100   
Enter the score for assignment #2: 75   
Enter the score for assignment #3: 82  
(and so, and so on.)

我真的不知道我怎么想把输入放在我创建的同一个循环中。 有没有人可以帮助我。我可以使用哪些代码,允许无限循环的输入沿同一行输入分配#x的分数:(输入)

3 个答案:

答案 0 :(得分:1)

您对include指令使用了错误的语法。而不是

include iostream
include fstream

必须有

#include <iostream>
#include <fstream>

该程序可以采用以下方式

#include <iostream>
#include <vector>


int main() 
{
    unsigned int program = 0;

    std::cout << "Enter the number of assignments that were graded: ";
    cin >> program;

    std::vector<unsigned int> scores( program );

    for ( unsigned int i = 0; i < program; i++ )
    {
        std::cout << "Enter the score for assignment # " << i + 1 << ':';
        std::cin >> scores[i];
    }

    // ...

您可以使用unsigned int

类型,而不是size_t类型

答案 1 :(得分:0)

  

我真的不知道我怎么想把输入放在同一个循环中

在for循环中放入另一个输入:

    for (int i=1; i <= program; i++) {
      cout << "Enter the score for assignment # " << i <<": "<< endl;
      int score;
      cin >> score;
      // ...
    }

编写循环或控制流程(ifelse)这样的语句

    for (int i=1; i <= program; i++)
         statement();

是危险的BTW。使用大括号{}总是更好。

答案 2 :(得分:0)

基本上,您需要在for循环中创建一个代码块:

vector<int> grades;

for (int i = 0; i < program; ++i )
{
  int temp_grade = 0;
  cout << "Enter the score for assignment #" << i <<": "; cin >> temp_grade;
  grades.push_back( temp_grade );
}

如果要使用某些vector项,可以使用下标或迭代器。

通过iterator s打印成绩:

for(vector<int>::iterator it = grades.cbegin(); it != grades.cend(); ++it)
    cout << *it << " ";