cin.Getline在for循环中出错
cin.getline messing up in for loop
好的,我正在尝试做这个程序,我必须让用户输入学生姓名,然后输入他们的考试成绩。我试着设置它,这样我就会有一个名字数组和一个成绩数组。我在向数组中添加名字时遇到了麻烦。我尝试在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:nn";
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 << "nnAverage 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。我一直在用它,所以它实际上很好。只是想确保您知道它刷新了缓冲区。
cout << studentNames[i] <<endl;
4:不知道这是干什么用的。阅读并扔掉下一行的第一个字符!!!!!!
cin.get();
5:注意,这工作得很好。因为>>操作符在搜索下一个分数时忽略换行符。
//Get a test score.
//cout << "Enter test score "
//<< (i + 1) << ": ";
//cin >> testScorePtr[i];
6:就像我上面预测的那样,你忘记删除一个数组。只用一个向量。任何你使用new/delete的地方,你都在写像C一样的代码。好的c++代码应该几乎没有删除(除非你在写智能指针/容器)。
delete [] testScorePtr;
7:你知道有一个std::sort方法
void sort(double* score, int size)
8:可以使用std::accumulate
double average(double* score, int numScores)
- 如何循环打印顶点结构
- C++ 循环屏障中的倒计时使用原子变量出错[请无锁的解决方案]
- 在C++中调用while循环内的函数时出错
- C++ 使用 OpenMP 时,如果 for 循环在 if else 语句中出错
- 在循环中重新声明 for 循环变量时出错
- 从 OpenMP 循环内部访问和编辑 Qmap 时出错
- 我这秒 for 循环哪里出错了
- R6010 执行后出错.if 语句在 for 循环中.[作业][中止已解决,发现新问题]
- 使用For循环时出错
- 我的 for 循环出错,无法弄清楚原因,我有一个"expected declaration"错误
- while循环中出错
- 在发布模式下测量Visual Studio(C++)中循环内方法的运行时时出错
- ISR中使用的循环缓冲区(声明为volatile)会出错.为什么?如何解决此问题
- c++循环引用,使用方法时出错,即使在前向声明之后
- 我的堆栈使用链表时出错.无法打印数字循环.(C++)
- 尝试使用cout在循环中打印数组时出错
- 与矢量大小一起使用时,for 循环中出错
- 嵌套 for 循环的 openmp 出错
- 在非常小的循环中出错
- cin.Getline在for循环中出错