c++ - cin.getline 在 for 循环中搞砸了

标签 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);
    }

最佳答案

您没有考虑换行符。

这一行:

cin >> numTestScores;

从输入中读取一个数字,但不是换行符。因此,如果您键入 8,您会读取 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:注意这工作正常。由于 >> 运算符在搜索下一个分数时会忽略换行符。

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

6:就像我上面预测的那样,您忘记删除其中一个数组。只需使用一个 vector 。在您使用 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)

关于c++ - cin.getline 在 for 循环中搞砸了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5828660/

相关文章:

javascript项目拼接自己超出列表

javascript - 将数字检索到数组中 - JavaScript

mysql - 在没有 mysql_data_seek 的情况下重置结果指针

c++ - 如何使用类型特征使这种数组到指针的转换明确?

c++ - C++ 17 POSIX信号量或condition_variable?

c++ - STL 迭代器的语法是如何实现的?

java - 一种返回 boolean 值的方法,该 boolean 值标识 2 个数组的值是否相同

c++ - 这个 std::cout 最终会打印垃圾或意外的东西吗?

c - 在 C 中用两个字符串初始化一个 const char * const *

c++ - 我的成员模板函数声明有什么问题?