cin.getline乱搞for循环

时间:2011-04-29 06:26:18

标签: c++ arrays pointers

好的我正在尝试这个程序,我必须让用户输入学生姓名,然后输入他们的考试成绩。我正在尝试设置它,所以我将拥有一系列名称和一系列成绩。我无法将名称添加到数组中。我试图在for循环中调用cin.getline()并将其分配给数组中的每个下标。然而,它失败了。有人能指出我正确的方向吗?

#include<iostream>
#include<iomanip>
#include<string>
using namespace std;

//Function prototypes
void sort(double*, int);
double average(double*, int);
void drop(double*, int);

int main()
{   
    char ch;
    char name[30];
    int numTestScores;
    string *studentNames;
    double *testScorePtr;
    double testAverage;

    //Get the number of test scores.
    cout << "\nHow many test scores will you enter? ";
    cin >> numTestScores;

    //Validate the input.
    /*while (numTestScores < 0)
    {
        cout << "The number cannot be negative.\n";
        cout << "Enter another number: ";
        cin >> numTestScores;
    }*/

    // Allocate an array to hold the test scores
    studentNames = new string[numTestScores];
    testScorePtr = new double[numTestScores];

    //Fill the array with test scores.
    for(int i = 0; i < numTestScores; i++)
    {


        cout << "Enter name and test score for test # "
        << (i+1) << " : "<< endl;
        cin.getline(name,30);
        studentNames[i] = name;
        cout << studentNames[i] <<endl; //I tried to use this to see if the names were going into the array






        cin.get();
    }

        //Get a test score.
        //cout << "Enter test score "
            //<< (i + 1) << ": ";
        //cin >> testScorePtr[i];

        //Validate the input.
        /*while (numTestScores < 0)
        {
            cout << "Negative scores are not allowed.\n";
            cout << "Enter another score for this test: ";
            cin >> testScorePtr[i];*/






    // Sort the test scores.
    sort(testScorePtr, numTestScores);



    //Display the resulting data.
    cout << "\nThe test scores in ascending "
        << "order, and their average, are:\n\n";
    cout << "Score" <<endl;
    cout << "----" <<endl;

    for (int j = 0; j < numTestScores; j++)
    {
        cout << "\n" << fixed << setprecision(2)
             << setw(6) << testScorePtr[j];
    }

    //Drop The Lowest Grade
    drop(testScorePtr, numTestScores);


// Get the average of the test scores.
    testAverage = average(testScorePtr, numTestScores);


    cout << "\n\nAverage score: " << setprecision(2) << fixed << testAverage <<endl <<endl;

//  Free the dynamically-allocated memory.
    delete [] testScorePtr;
    testScorePtr = 0;

    return 0;
}


    //****************************************
    //Function sort
    //This function performs a selection sort
    //on the array pointed to by the score
    //parameter into ascending order. The size
    //parameter holds the number of elements.
    //*****************************************

    void sort(double* score, int size)
    { 
      int startScan, minIndex;
      double minValue;

      for (startScan = 0; startScan < (size - 1); startScan++)
      {
          minIndex = startScan;
          minValue = score[startScan];
          for(int index = startScan + 1; index < size; index++)
          {
              if (score[index] < minValue)
              {
                  minValue = score[index];
                  minIndex = index;
              }
          }
          score[minIndex] = score[startScan];
          score[startScan] = minValue;
      }
    }

    void drop(double* score, int size)
    {

        score[0] = 0;
    }

    //*************************************************
    //Function average
    //This function calculates and returns the 
    //average of the values stored in the array
    //passed into the scores parameter. The
    //parameter numScors holds the number of elements in the array

    double average(double* score, int numScores)
    {
        double total = 0; //Accumulator
        numScores--;
        //Calculate the total of the scores.
        for (int k = 0; k <= numScores ; k++)
        {
            total += score[k];
        }
        //Return the average score.
        return (total/numScores);
    }

1 个答案:

答案 0 :(得分:2)

您没有考虑换行符。

这一行:

cin >> numTestScores;

从输入中读取一个数字,但不是换行符。因此,如果您输入8&lt; enter&gt;你读了8但是没有从输入中读取换行符 所以你第一次进入循环并执行此操作:

cin.getline(name,30);

这将读取您在8之后键入的新行字符(而不是其他内容)。

其他几个陷阱...

1)忘记阅读并扔掉换行符。

cin >> numTestScores;

解决方案:

// 1: Read the line into a string then read the value from the string.
std::string testScoresString;
std::getline(std::cin, testScoresString);

std::stringstream testScoreStream(testScoreString);
testScoreStream >> numTestScores

// 2: Use boost::lexical cast on the string stream:
std::string testScoresString;
std::getline(std::cin, testScoresString);

testScoreStream = boost::lexical_cast<int>(testScoreString);

// 3: Read number then ignore input to the new line character
cin >> numTestScores;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

2:不要在C ++代码中使用new / delete
你可以使用新的动态对象,但记住要删除它们很难。您应该使用智能指针或容器来控制动态对象的生命周期。

studentNames = new string[numTestScores];
testScorePtr = new double[numTestScores];

在这种情况下,最好使用std :: vector。

std::vector<std::string> studentNames(numTestScores);
std::vector<double>      testScorePtr(numTestScores);

3:不要将固定大小的数组用于用户输入:

    cin.getline(name,30);

您只是要求用户崩溃您的程序。输入一个真正的长名称 使用将行读入std :: string的版本。字符串将根据需要进行扩展。

std::getline(std::cin, studentNames[i]);

4:你不需要在这里使用endl。如果希望缓冲区刷新,请使用endl。我一直用它,所以它实际上很好。只是想确保你知道它冲刷了缓冲区。

    cout << studentNames[i] <<endl;

4:不确定这是为了什么。阅读并丢掉下一行的第一个字符!!!!!!

    cin.get();

5:注意这很好用。作为&gt;&gt;运算符在搜索下一个分数时忽略换行符。

    //Get a test score.
    //cout << "Enter test score "
        //<< (i + 1) << ": ";
    //cin >> testScorePtr[i];

6:就像我上面预测的那样,你忘了删除其中一个阵列。只需使用矢量。你使用new / delete的任何地方你都在编写类似C的代码。好的C ++代码几乎没有删除它(除非你正在编写智能指针/容器)。

delete [] testScorePtr;

7:你知道有std::sort method

void sort(double* score, int size)

8:你可以靠近std::accumulate

double average(double* score, int numScores)