从控制台读取字符串并将其存储在数组中
Reading strings from the console and storing them in an array
我对如何在数组中存储字符串感到困惑。该程序的目的是从控制台接收一些学生和一些测验,然后计算每个学生所述测验成绩的平均值,这很容易。尽管我在尝试输入学生姓名时遇到了一些问题(根据用户给我的学生人数,有1-10个字符串)。我唯一能想到的接收这些数据的方法是使用for循环,因为我需要读取的名称数量由用户输入决定。我想将名称存储在一个数组中,但我不确定如何做到这一点。如有任何帮助,我们将不胜感激。下面的代码。
int main()
{
int students = 0;
getStudents(students);
int quizzes = 0;
getQuizzes(quizzes);
char* studentArray = new char[students];
int* quizArray = new int[quizzes];
double* studentAverage = new double[students];
char student_name[20];
for(int i = 0; i < students; i++)
{
cout << "Enter the students name: ";
cin.get (student_name, 20);
cin.ignore(' ','n');
studentArray[i]=student_name;
for(int j = 0; j < quizzes; j++)
{
cout << "Enter quiz " << j+1 << ":";
cin >> quizArray[j];
}
studentAverage[i] = calculateAvergage(quizArray,quizzes);
}
^主程序。问题发生在外部for循环中。我被迫接受循环中的名称,因为在运行时之前我不知道要接受多少名称。循环结束后,我还必须稍后在程序中显示名称,这样我就不能只做一个简单的cout<lt;循环内部。
for(int i = 0; i < students; i++)
{
cout << studentArray[i] << setw(10) << studentAverage[i] << endl << endl;
}
^在程序结束时显示数据的循环。
我还将添加输出应该是什么样子,以进行一点澄清
How many students? 2
How many quizzes? 3
Enter the students name: John Smith
Enter Quiz 1: 90
Enter Quiz 2: 80
Enter Quiz 3: 75
Enter the students name: John Jones
Enter Quiz 1: 100
Enter Quiz 2: 90
Enter Quiz 3: 80
Student Quiz Average
---------------------------------
John Smith 81.67
John Jones 90.00
You can modify the below code to suit your needs. It takes a string and integer.
#include <iostream>
#include<vector>
#include <string>
int main()
{
std::string name;
int num;
std::vector<std::string> stringList;
std::vector<int> intList;
while( std::cin >> name >> num )
{
//enter stop and 0 to stop
if (!name.compare("stop") && num == 0) break;
stringList.push_back(name);
intList.push_back(num);
}
std::copy(stringList.begin(), stringList.end(), std::ostream_iterator<std::string> (std::cout,","));
std::cout << std::endl;
std::copy(intList.begin(), intList.end(), std::ostream_iterator<int>(std::cout ,",") );
std::cout << std::endl;
return 0;
}
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组